MVC_防止HttpPost重複提交

來源:互聯網
上載者:User

標籤:rar   不一致   ace   ado   void   .com   names   cti   put   

重複提交的情境很常見,可能是當時伺服器延遲的原因,如購物車物品疊加,重複提交多個訂單。常見的解決方案是提交後把Button在用戶端Js禁用,或是用Js禁止後退鍵等。在ASP.NET MVC 3 Web Application中 如何去防止這類HTTP-Post的重複提交呢? 我們可以藉助Session,放置一個Token在View/Page上,然後在Server端去驗證是不是同一個Token來判斷此次Http-Post是否有效。看下面的代碼:  首先定義一個介面,便於擴充。

public interface IPageTokenView{    /// <summary>    /// Generates the page token.    /// </summary>    string GeneratePageToken();    /// <summary>    /// Gets the get last page token from Form    /// </summary>    string GetLastPageToken { get; }    /// <summary>    /// Gets a value indicating whether [tokens match].    /// </summary>    /// <value>    ///   <c>true</c> if [tokens match]; otherwise, <c>false</c>.    /// </value>    bool TokensMatch { get; }}


定義一個Abstract Class,包含一個

public abstract class PageTokenViewBase : IPageTokenView{    public static readonly string HiddenTokenName = "hiddenToken";    public static readonly string SessionMyToken = "Token";    /// <summary>    /// Generates the page token.    /// </summary>    /// <returns></returns>    public abstract string GeneratePageToken();    /// <summary>    /// Gets the get last page token from Form    /// </summary>    public abstract string GetLastPageToken { get; }    /// <summary>    /// Gets a value indicating whether [tokens match].    /// </summary>    /// <value>    ///   <c>true</c> if [tokens match]; otherwise, <c>false</c>.    /// </value>    public abstract bool TokensMatch { get; }  }


接著是實現SessionPageTokenView類型,記得需要在驗證通過後產生新的Token,對於這個Class是把它放到Session中。

    public class SessionPageTokenView : PageTokenViewBase    {        #region PageTokenViewBase        /// <summary>        /// Generates the page token.        /// </summary>        /// <returns></returns>        public override string GeneratePageToken()        {            if (HttpContext.Current.Session[SessionMyToken] != null)            {                return HttpContext.Current.Session[SessionMyToken].ToString();            }            else            {                var token = GenerateHashToken();                HttpContext.Current.Session[SessionMyToken] = token;                return token;            }        }        /// <summary>        /// Gets the get last page token from Form        /// </summary>        public override string GetLastPageToken        {            get            {                return HttpContext.Current.Request.Params[HiddenTokenName];            }        }        /// <summary>        /// Gets a value indicating whether [tokens match].        /// </summary>        /// <value>        ///   <c>true</c> if [tokens match]; otherwise, <c>false</c>.        /// </value>        public override bool TokensMatch        {            get            {                string formToken = GetLastPageToken;                if (formToken != null)                {                    if (formToken.Equals(GeneratePageToken()))                    {                        //Refresh token                        HttpContext.Current.Session[SessionMyToken] = GenerateHashToken();                        return true;                    }                }                return false;            }        }        #endregion         #region Private Help Method        /// <summary>        /// Generates the hash token.        /// </summary>        /// <returns></returns>        private string GenerateHashToken()        {            return Utility.Encrypt(                HttpContext.Current.Session.SessionID + DateTime.Now.Ticks.ToString());        }         #endregion



這裡有到一個簡單的加密方法,你可以實現自己的加密方法. 

public static string Encrypt(string plaintext){    string cl1 = plaintext;    string pwd = string.Empty;    MD5 md5 = MD5.Create();    byte[] s = md5.ComputeHash(Encoding.Unicode.GetBytes(cl1));    for (int i = 0; i < s.Length; i++)    {        pwd = pwd + s[i].ToString("X");    }    return pwd;}


我們再來編寫一個Attribute繼承FilterAttribute, 實現IAuthorizationFilter介面。然後比較Form中Token與Session中是否一致,不一致就Throw Exception. Tips:這裡最好使用依賴注入IPageTokenView類型,增加Logging 等機制 

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]public sealed class ValidateReHttpPostTokenAttribute : FilterAttribute, IAuthorizationFilter{    public IPageTokenView PageTokenView { get; set; }    /// <summary>    /// Initializes a new instance of the <see cref="ValidateReHttpPostTokenAttribute"/> class.    /// </summary>    public ValidateReHttpPostTokenAttribute()    {        //It would be better use DI inject it.        PageTokenView = new SessionPageTokenView();    }    /// <summary>    /// Called when authorization is required.    /// </summary>    /// <param name="filterContext">The filter context.</param>    public void OnAuthorization(AuthorizationContext filterContext)    {        if (filterContext == null)        {            throw new ArgumentNullException("filterContext");        }        if (!PageTokenView.TokensMatch)        {            //log...            throw new Exception("Invaild Http Post!");        }          }}


還需要一個HtmlHelper的擴充方法:

public static HtmlString GenerateVerficationToken(this HtmlHelper htmlhelper){    string formValue = Utility.Encrypt(HttpContext.Current.Session.SessionID+DateTime.Now.Ticks.ToString());    HttpContext.Current.Session[PageTokenViewBase.SessionMyToken] = formValue;    string fieldName = PageTokenViewBase.HiddenTokenName;    TagBuilder builder = new TagBuilder("input");    builder.Attributes["type"] = "hidden";    builder.Attributes["name"] = fieldName;    builder.Attributes["value"] = formValue;    return new HtmlString(builder.ToString(TagRenderMode.SelfClosing));}


將輸出這類的HtmlString: 

<input name="hiddenToken" type="hidden" value="1AB01826F590A1829E65CBD23CCE8D53" />


我們建立一個叫_ViewToken.cshtml的Partial View,這樣便於模組化,讓我們輕易加入到具體View裡,就兩行代碼,第一行是擴充方法NameSpace

 

@using Mvc3App.Models;@Html.GenerateVerficationToken()

假設我們這裡有一個簡單的Login.cshtml,然後插入其中:
   <form method="post" id="form1" action="@Url.Action("Index")">    <p>        @Html.Partial("_ViewToken")        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>

這裡我們Post的Index Action,看Controller代碼,我們在Index上加上ValidateReHttpPostToken的attribute.


[HttpPost][ValidateReHttpPostToken]public ActionResult Index(FormCollection formCollection){    return View();}public ActionResult Login(){    return View();}

MVC_防止HttpPost重複提交

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.