我們知道,在ASP.NET MVC中,要從一個(gè)Action跳轉(zhuǎn)到另一個(gè)Action,通常是用一系列以“Redirect”開頭的方法
Redirect
RedirectToAction
RedirectToRoute
之類的。
但是使用Redirect系列的方法進(jìn)行跳轉(zhuǎn)時(shí),默認(rèn)是使用GET方法的,也就是說(shuō),如果你的跳轉(zhuǎn)請(qǐng)求帶有參數(shù),那么這些參數(shù)將全部暴露在跳轉(zhuǎn)后的url中,增加了不安全性(特別是如果參數(shù)中包含密碼、密鑰等等敏感數(shù)據(jù))
于是就想到了用POST方法傳遞數(shù)據(jù),這樣至少一般的訪問(wèn)者無(wú)法從url中獲取敏感信息。但是仔細(xì)查閱了MSDN和StackOverflow,得到的答案是“Redirect方法不支持POST”。
好在StackOverflow上找到一個(gè)回答 點(diǎn)我 ,倒是給我一些啟發(fā)。直接POST不行,那就間接POST,先通過(guò)一個(gè)GET方法獲取某個(gè)頁(yè)面,然后以這個(gè)頁(yè)面為中介將數(shù)據(jù)POST給真正要處理請(qǐng)求的頁(yè)面。
下面給出一個(gè)示例代碼。在這個(gè)示例代碼中,有兩個(gè)頁(yè)面Login和AfterLogin,要求在Login中輸入用戶名和密碼后跳轉(zhuǎn)到AfterLogin,并攜帶一個(gè)由UserAppModel定義的數(shù)據(jù)列表
public class UserAppModel
{
public string UserId { get; set; }
public string ClientId { get; set; }
public string RedirectUri { get; set; }
}
這些信息將在使用GET方法加載Login頁(yè)面時(shí)獲取。
public ActionResult Login(string client_id, string redirect_uri)
{
HttpCookie cookie = new HttpCookie("app");
cookie["client_id"] = client_id;
cookie["redirect_uri"] = redirect_uri;
Response.Cookies.Add(cookie);
return View();
}
界面設(shè)計(jì)就省略了,無(wú)非是兩個(gè)文本框和一個(gè)submit按鈕。
之后對(duì)Login要有個(gè)HttpPost方法來(lái)接收登錄數(shù)據(jù),并構(gòu)造UserAppModel的數(shù)據(jù)發(fā)到新的AfterLogin頁(yè)面。
[HttpPost]
public ActionResult Login(UserModel model)
{
if (ModelState.IsValid)
{
HttpCookie cookie = Request.Cookies["app"];
if (cookie != null)
{
if (model.UserId == "AAA" && model.Password == "aaa")
{
UserAppModel newModel = new UserAppModel();
newModel.UserId = model.UserId;
newModel.ClientId = cookie["client_id"];
newModel.RedirectUri = cookie["redirect_uri"];
TempData["model"] = newModel;
return RedirectToAction("AfterLogin", "Home");
}
ViewBag.Message = "Login error! Invalid user ID or password.";
}
}
return View();
}
AfterLogin需要兩個(gè)方法,一個(gè)采用GET方式,一個(gè)采用POST方式,通過(guò)GET方式的頁(yè)面去調(diào)用POST方式的頁(yè)面,就實(shí)現(xiàn)了使用POST的重定向
//
// POST: /Home/AfterLogin
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AfterLogin(UserAppModel model)
{
ViewData["model"] = model;
return View(model);
}
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult AfterLogin()
{
return AfterLogin(TempData["model"] as UserAppModel);
}
結(jié)論:Redirect系列方法不支持POST,但是可以通過(guò)間接的做法實(shí)現(xiàn)POST方式的重定向。
更多信息請(qǐng)查看IT技術(shù)專欄