ASP.NET MVC 4.0 Features

MVC Anti forgery for HTTP Headers validator

//WEB API ANTIFORGERY CUSTOM ACTION FILTER ATTRIBUTE
public class AntiForgeryValidateRequests : BaseActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext filterContext)
    {
        if (filterContext != null && filterContext.RequestContext != null && filterContext.Request != null)
        {
            string cookieToken = "";
            string formToken = "";

            IEnumerable<string> tokenHeaders = filterContext.Request.Headers.GetValues(Constant.RequestVerificationToken);
            if (tokenHeaders != null && tokenHeaders.Count() > 0)
            {
                string[] tokens = tokenHeaders.First().Split(':');
                if (tokens.Length == 2)
                {
                    cookieToken = tokens[0].Trim();
                    formToken = tokens[1].Trim();
                }
            }

            System.Web.Helpers.AntiForgery.Validate(cookieToken, formToken);
        }

        base.OnActionExecuting(filterContext);
    }        
}

JavaScript,

$.ajax({
    url: requestURL,
    type: 'POST',
    contentType: "application/json; charset=utf-8",
    data: null,
    beforeSend: function (xhr) {
        xhr.setRequestHeader("Request_Token", request_token);
        xhr.setRequestHeader("Request_Order", request_order);
    },
    async: true,
    cache: false,
    success: function (data) {
        if (data !== undefined && data !== null) {
            if (data.Code == "OK") {
                alertDialog('info', 'Information', "Success", data.Message, null);
                return false;
            }
            else if (data.Code == "ERROR") {
                alertDialog('error', 'Error', 'Error', data.Message, null);
                return false;
            }
        }
    }
});

Go for more,
https://nozzlegear.com/blog/send-and-validate-an-asp-net-antiforgerytoken-as-a-request-header
http://www.codeproject.com/Tips/879039/MVC-Anti-forgery-validator-for-HTTP-Headers
http://stackoverflow.com/questions/19788916/how-to-make-ajax-request-with-anti-forgery-token-in-mvc
http://stackoverflow.com/questions/4074199/jquery-ajax-calls-and-the-html-antiforgerytoken

ANIL SINGH

Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
My Blogs - http://www.code-sample.com and http://www.code-sample.xyz
My Books - Buy Books Online at Best Prices

You Might Also Like
Post a Comment
www.code-sample.com/. Powered by Blogger.