Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 707951
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T04:20:08+00:00 2026-05-14T04:20:08+00:00

I’m in the process of adding some UI functionality to a hybrid WebForms/MVC site.

  • 0

I’m in the process of adding some UI functionality to a hybrid WebForms/MVC site. In this case, I’m adding some AJAX UI features to a WebForms page (via jQuery), and the data is coming from an MVC JsonResult. Everything is working 100%, with one exception:

I would like to implement the XSRF protection of AntiForgeryToken. I have used it in combination with the ValidateAntiForgeryToken attribute on my pure MVC applications, but would like to know how to implement the Html.AntiForgeryToken() method in WebForms. Here’s an example using a UrlHelper.

I’m having some trouble getting ViewContext / RequestContext “mocked” up correctly. How should I go about using HtmlHelpers within a WebForms page?

Edit:
I’m looking to retrieve the AntiForgeryToken from my WebForms page, not from the MVC JsonResult.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-14T04:20:09+00:00Added an answer on May 14, 2026 at 4:20 am

    The key method is in the MVC source code: GetAntiForgeryTokenAndSetCookie

    This creates an instance of an internal sealed class called AntiForgeryData.

    The instance is serialised into a cookie “__RequestVerificationToken_” + a base 64 encoded version of the application path.

    The same instance of AntiForgeryData is serialised into a hidden input.

    The unique part of the AntiForgeryData is got with an RNGCryptoServiceProvider.GetBytes()

    All of this could be spoofed in a WebForms page, the only messy bit is the serialisation of the hidden sealed class. Unfortunately the key method (GetAntiForgeryTokenAndSetCookie) relies on ViewContext.HttpContext.Request to get at the cookies, while the WebForm needs to use HttpContext.Current.Request instead.


    Update

    Not much testing and a lot of code, but I think I’ve cracked this with a little reflection. Where I’ve used reflection I’ve left the equivalent line commented out above:

    using System;
    using System.Reflection;
    using System.Web;
    using System.Web.Mvc;
    
    /// <summary>Utility to provide MVC anti forgery tokens in WebForms pages</summary>
    public class WebFormAntiForgery
    {
        /// <summary>Create an anti forgery token in a WebForms page</summary>
        /// <returns>The HTML input and sets the cookie</returns>
        public static string AntiForgeryToken()
        {
            string formValue = GetAntiForgeryTokenAndSetCookie();
    
            // string fieldName = AntiForgeryData.GetAntiForgeryTokenName(null);
            var mvcAssembly = typeof(HtmlHelper).Assembly;
            var afdType = mvcAssembly.GetType("System.Web.Mvc.AntiForgeryData");
            string fieldName = Convert.ToString(afdType.InvokeMember(
                "GetAntiForgeryTokenName",
                BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.InvokeMethod,
                null,
                null,
                new object[] { null }));
    
            TagBuilder builder = new TagBuilder("input");
            builder.Attributes["type"] = "hidden";
            builder.Attributes["name"] = fieldName;
            builder.Attributes["value"] = formValue;
            return builder.ToString(TagRenderMode.SelfClosing);
        }
    
        static string GetAntiForgeryTokenAndSetCookie()
        {
            var mvcAssembly = typeof(HtmlHelper).Assembly;
            var afdType = mvcAssembly.GetType("System.Web.Mvc.AntiForgeryData");
    
            // new AntiForgeryDataSerializer();
            var serializerType = mvcAssembly.GetType("System.Web.Mvc.AntiForgeryDataSerializer");
            var serializerCtor = serializerType.GetConstructor(new Type[0]);
            object serializer = serializerCtor.Invoke(new object[0]); 
    
            // string cookieName = AntiForgeryData.GetAntiForgeryTokenName(HttpContext.Current.Request.ApplicationPath);
            string cookieName = Convert.ToString(afdType.InvokeMember(
                "GetAntiForgeryTokenName",
                BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.InvokeMethod,
                null,
                null,
                new object[] { HttpContext.Current.Request.ApplicationPath }));
    
            // AntiForgeryData cookieToken;
            object cookieToken;
            HttpCookie cookie = HttpContext.Current.Request.Cookies[cookieName];
            if (cookie != null)
            {
                // cookieToken = Serializer.Deserialize(cookie.Value);
                cookieToken = serializerType.InvokeMember("Deserialize", BindingFlags.InvokeMethod, null, serializer, new object[] { cookie.Value });
            }
            else
            {
                // cookieToken = AntiForgeryData.NewToken();
                cookieToken = afdType.InvokeMember(
                    "NewToken",
                    BindingFlags.Public | BindingFlags.Static | BindingFlags.InvokeMethod,
                    null,
                    null,
                    new object[0]);
    
                // string cookieValue = Serializer.Serialize(cookieToken);
                string cookieValue = Convert.ToString(serializerType.InvokeMember("Serialize", BindingFlags.InvokeMethod, null, serializer, new object[] { cookieToken }));
    
                var newCookie = new HttpCookie(cookieName, cookieValue) { HttpOnly = true };
    
                HttpContext.Current.Response.Cookies.Set(newCookie);
            }
    
            // AntiForgeryData formToken = new AntiForgeryData(cookieToken)
            // {
            //     CreationDate = DateTime.Now,
            //     Salt = salt
            // };
            var ctor = afdType.GetConstructor(new Type[] { afdType });
            object formToken = ctor.Invoke(new object[] { cookieToken });
    
            afdType.InvokeMember("CreationDate", BindingFlags.SetProperty, null, formToken, new object[] { DateTime.Now });
            afdType.InvokeMember("Salt", BindingFlags.SetProperty, null, formToken, new object[] { null });
    
            // string formValue = Serializer.Serialize(formToken);
            string formValue = Convert.ToString(serializerType.InvokeMember("Serialize", BindingFlags.InvokeMethod, null, serializer, new object[] { formToken }));
            return formValue;
        }
    }
    

    Usage is then similar to MVC:

    WebFormAntiForgery.AntiForgeryToken()
    

    It creates the same cookie and the same HTML as the MVC methods.

    I haven’t bothered with the salt and domain methods, but they would be fairly easy to add in.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 379k
  • Answers 379k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer My question, what do I need to do so I… May 14, 2026 at 9:33 pm
  • Editorial Team
    Editorial Team added an answer There is resiliency built-in to the IIS6/7 process model. If… May 14, 2026 at 9:33 pm
  • Editorial Team
    Editorial Team added an answer Remus explains explains how to do it in his blog.… May 14, 2026 at 9:33 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.