本文轉自:http://www.cnblogs.com/ryuasuka/p/3604452.html?utm_source=tuicool
我們知道,在ASP.NET MVC中,要從一個Action跳轉到另一個Action,通常是用一系列以“Redirect”開頭的方法
- Redirect
- RedirectToAction
- RedirectToRoute
之類的。
但是使用Redirect系列的方法進行跳轉時,默認是使用GET方法的,也就是說,如果你的跳轉請求帶有參數,那么這些參數將全部暴露在跳轉后的url中,增加了不安全性(特別是如果參數中包含密碼、密鑰等等敏感數據)
於是就想到了用POST方法傳遞數據,這樣至少一般的訪問者無法從url中獲取敏感信息。但是仔細查閱了MSDN和StackOverflow,得到的答案是“Redirect方法不支持POST”。
好在StackOverflow上找到一個回答 點我 ,倒是給我一些啟發。直接POST不行,那就間接POST,先通過一個GET方法獲取某個頁面,然后以這個頁面為中介將數據POST給真正要處理請求的頁面。
下面給出一個示例代碼。在這個示例代碼中,有兩個頁面Login和AfterLogin,要求在Login中輸入用戶名和密碼后跳轉到AfterLogin,並攜帶一個由UserAppModel定義的數據列表
public class UserAppModel { public string UserId { get; set; } public string ClientId { get; set; } public string RedirectUri { get; set; } }
這些信息將在使用GET方法加載Login頁面時獲取。
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(); }
界面設計就省略了,無非是兩個文本框和一個submit按鈕。
之后對Login要有個HttpPost方法來接收登錄數據,並構造UserAppModel的數據發到新的AfterLogin頁面。
[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需要兩個方法,一個采用GET方式,一個采用POST方式,通過GET方式的頁面去調用POST方式的頁面,就實現了使用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); }
結論:Redirect系列方法不支持POST,但是可以通過間接的做法實現POST方式的重定向。