使用Post/Redirect/Get實現Asp.net防止表單重復提交


      前面的Post有提到解決Web中表單重復提交的方法,實際上表單重復提交的問題不單是Asp.net,其它動態Page都有。讓我們看下面的圖示:

PostRedirectGet_DoubleSubmitProblem
    

然后在刷新頁面時經常看到提示框在IE中:

IE_3

Google Chrome:

Chrome_3

Firefox:

Firefox_thumb_1

 

最簡單的解決方法就是使用Post-Redirect-Get模式,就是Http-Post完后,馬上做Redirect操作,接下來那個頁面是Get。這時用戶強制按F5刷新也沒有用了。最終實現的效果圖:

PostRedirectGet_DoubleSubmitSolution

 

那在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>
<h2>Object moved to <a href="/Security?fusername=admin">here</a>.</h2>
</body></html>

在現在大多數的Web應用程序中都使用是Http 302的重定向。Http 1.1說明書中引用HTTP 303就是用來應對這種用戶提交表單后可以在瀏覽器安全的刷新場景。 HTTP 303 意義是這樣的:

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:

/// <summary>
/// SeeOtherRedirectResult
/// </summary>
public class SeeOtherRedirectResult : ActionResult
{
    private string _url;

    /// <summary>
    /// Initializes a new instance of the <see cref="SeeOtherRedirectResult"/> class.
    /// </summary>
    /// <param name="url">Target URL.</param>
    public SeeOtherRedirectResult(string url)
    {
        _url = url;
    }

    /// <summary>
    /// Enables processing of the result of an action method by a custom type that inherits from the <see cref="T:System.Web.Mvc.ActionResult"/> class.
    /// </summary>
    /// <param name="context">The context in which the result is executed. The context information includes the controller, HTTP content, request context, and route data.</param>
    public override void ExecuteResult(ControllerContext context)
    {
        context.HttpContext.Response.StatusCode = 303;
        context.HttpContext.Response.RedirectLocation = _url;
    }
}


然后Action中使用它,來實現Http 303的重定向。:

[HttpPost]
public ActionResult LoginVerify(string fusername, string fpassword)
{
    return new SeeOtherRedirectResult(Url.Action("Index", "Security", new { fusername = fusername }));
}


運行時,我們來看Http Response RAW:

HTTP/1.1 303 See Other
Cache-Control: private
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 03:05:37 GMT
Content-Length: 0


完了,希望對您Web開發有幫助。如有任何問題請留言!

您可能感興趣的文章:

Asp.net MVC中防止HttpPost重復提交
JQuery防止退格鍵網頁后退

 


作者:Petter Liu
出處:http://www.cnblogs.com/wintersun/
本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,否則保留追究法律責任的權利。
該文章也同時發布在我的獨立博客中-Petter Liu Blog


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM