前面的Post有提到解决Web中表单重复提交的方法,实际上表单重复提交的问题不单是Asp.net,其它动态Page都有。让我们看下面的图示:
然后在刷新页面时经常看到提示框在IE中:
Google Chrome:
Firefox:
最简单的解决方法就是使用Post-Redirect-Get模式,就是Http-Post完后,马上做Redirect操作,接下来那个页面是Get。这时用户强制按F5刷新也没有用了。最终实现的效果图:
那在Asp.net MVC中如何去做呢,看下面简单View代码:
一个包含两个Input的表单:
<form method&#61;"post" id&#61;"form1" action&#61;"/Security/LoginVerify"><p> UserName:<input type&#61;"text" id&#61;"fusername" name&#61;"fusername" /><br />Password:<input type&#61;"password" id&#61;"fpassword" name&#61;"fpassword" /><input type&#61;"submit" value&#61;"Sign-in" />p>form>
Index Action 在这里做Get的操作, LoginVerify 在这里是Post的目标Action
[HttpPost]
public ActionResult LoginVerify(string fusername, string fpassword)
{return this.RedirectToAction("Index", "Security", new { fusername &#61; fusername });
}
public ActionResult Index(string fusername)
{ViewBag.UserName &#61; fusername &#43; " login success!";return View();
}
对应请求时的HTTP Request RAW是这样的:
POST http://localhost:91/Security/LoginVerify HTTP/1.1
Accept: text/html, application/xhtml&#43;xml, */*
Referer: http://localhost:91/Security/Login
Accept-Language: en-US,zh-CN;q&#61;0.5
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate
Host: localhost:91
Content-Length: 71
Connection: Keep-Alive
Pragma: no-cache
COOKIE: ASP.NET_SessionId&#61;qwwlp4rmjnzbsq3ob4dmcg3q
Http Response RAW:
HTTP/1.1 302 Found
Cache-Control: private
Content-Type: text/html; charset&#61;utf-8
Location: /Security?fusername&#61;admin
Server: Microsoft-IIS/7.5
X-AspNetMvc-Version: 3.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Sat, 24 Mar 2012 02:54:26 GMT
Content-Length: 142
Object moved to here.
在现在大多数的Web应用程序中都使用是Http 302的重定向。Http 1.1说明书中引用HTTP 303就是用来应对这种用户提交表单后可以在浏览器安全的刷新场景。 HTTP 303 意义是这样的&#xff1a;
Used to tell the client that the resource should be fetched using a different URL. This
new URL is in the Location header of the response message. Its main purpose is to
allow responses to POST requests to direct a client to a resource.
在Asp.net MVC可以这些去实现一个自定义ActionResult:
///
///
///
public class SeeOtherRedirectResult : ActionResult
{private string _url;///
}
然后Action中使用它&#xff0c;来实现Http 303的重定向。&#xff1a;
[HttpPost]
public ActionResult LoginVerify(string fusername, string fpassword)
{return new SeeOtherRedirectResult(Url.Action("Index", "Security", new { fusername &#61; fusername }));
}
运行时&#xff0c;我们来看Http Response RAW:
HTTP/1.1 303 See Other
Cache-Control: private
Location: /Security?fusername&#61;admin
Server: Microsoft-IIS/7.5
X-AspNetMvc-Version: 3.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Sat, 24 Mar 2012 03:05:37 GMT
Content-Length: 0
完了&#xff0c;希望对您Web开发有帮助。如有任何问题请留言!
您可能感兴趣的文章&#xff1a;
Asp.net MVC中防止HttpPost重复提交
JQuery防止退格键网页后退
作者&#xff1a;Petter Liu
出处&#xff1a;http://www.cnblogs.com/wintersun/
本文版权归作者和博客园共有&#xff0c;欢迎转载&#xff0c;但未经作者同意必须保留此段声明&#xff0c;且在文章页面明显位置给出原文连接&#xff0c;否则保留追究法律责任的权利。
该文章也同时发布在我的独立博客中-Petter Liu Blog。