html5中文学习网

您的位置: 首页 > 网络编程 > ASP.NET » 正文

ASP.NET MVC实现POST方式的Redirect_.NET教程_编程技术

[ ] 已经帮助:人解决问题

我们知道,在ASP.NET MVC中,要从一个Action跳转到另一个Action,通常是用一系列以“Redirect”开头的方法uNVHTML5中文学习网 - HTML5先行者学习网

  • Redirect
  • RedirectToAction
  • RedirectToRoute

之类的。uNVHTML5中文学习网 - HTML5先行者学习网

但是使用Redirect系列的方法进行跳转时,默认是使用GET方法的,也就是说,如果你的跳转请求带有参数,那么这些参数将全部暴露在跳转后的url中,增加了不安全性(特别是如果参数中包含密码、密钥等等敏感数据)uNVHTML5中文学习网 - HTML5先行者学习网

于是就想到了用POST方法传递数据,这样至少一般的访问者无法从url中获取敏感信息。但是仔细查阅了MSDN和StackOverflow,得到的答案是“Redirect方法不支持POST”。uNVHTML5中文学习网 - HTML5先行者学习网

好在StackOverflow上找到一个回答 点我  ,倒是给我一些启发。直接POST不行,那就间接POST,先通过一个GET方法获取某个页面,然后以这个页面为中介将数据POST给真正要处理请求的页面。uNVHTML5中文学习网 - HTML5先行者学习网

下面给出一个示例代码。在这个示例代码中,有两个页面Login和AfterLogin,要求在Login中输入用户名和密码后跳转到AfterLogin,并携带一个由UserAppModel定义的数据列表uNVHTML5中文学习网 - HTML5先行者学习网

public class UserAppModel{    public string UserId { get; set; }    public string ClientId { get; set; }    public string RedirectUri { get; set; }}

这些信息将在使用GET方法加载Login页面时获取。uNVHTML5中文学习网 - HTML5先行者学习网

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按钮。uNVHTML5中文学习网 - HTML5先行者学习网

之后对Login要有个HttpPost方法来接收登录数据,并构造UserAppModel的数据发到新的AfterLogin页面。uNVHTML5中文学习网 - HTML5先行者学习网

[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的重定向uNVHTML5中文学习网 - HTML5先行者学习网

//// 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方式的重定向。uNVHTML5中文学习网 - HTML5先行者学习网

uNVHTML5中文学习网 - HTML5先行者学习网
uNVHTML5中文学习网 - HTML5先行者学习网
(责任编辑:)
推荐书籍
推荐资讯
关于HTML5先行者 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 人才招聘 - 帮助