使用Post/Redirect/Get实现Asp.net防止表单重复提交

然后在刷新页面时经常看到提示框在IE中:

Google Chrome:

Firefox:

最简单的解决方法就是使用Post-Redirect-Get模式,就是Http-Post完后,马上做Redirect操作,接下来那个页面是Get。这时用户强制按F5刷新也没有用了。最终实现的效果图:

那在Asp.net MVC中如何去做呢,看下面简单View代码:
一个包含两个Input的表单:
<form method="post" id="form1" action="/Security/LoginVerify">
<p>
UserName:<input type="text" id="fusername" name="fusername" /><br />
Password:<input type="password" id="fpassword" name="fpassword" />
<input type="submit" value="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 = fusername });
}
public ActionResult Index(string fusername)
{
ViewBag.UserName = fusername + " login success!";
return View();
}
对应请求时的HTTP Request RAW是这样的:
POST http://localhost:91/Security/LoginVerify HTTP/1.1
Accept: text/html, application/xhtml+xml, */*
Referer: http://localhost:91/Security/Login
Accept-Language: en-US,zh-CN;q=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=qwwlp4rmjnzbsq3ob4dmcg3q
Http Response RAW:
HTTP/1.1 302 Found
Cache-Control: private
Content-Type: text/html; charset=utf-8
Location: /Security?fusername=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
<html><head><title>Object moved</title></head><body>
相关新闻>>
- 发表评论
-
- 最新评论 更多>>