CuriousBenjamin
CuriousBenjamin

Reputation: 719

Anti-Forgery token usage between MVC pages to classic ASP.NET pages

I have an application which has 80% of it's part in ASP.NET MVC 2. I am using Anti-forgery token to avoid Cross-Site Request Forgery.

Say I have an action method -

public JsonResult AddMenuFavorite(int id) {
    // code
}

which uses the token to prevent CSRF. I have various links in my MVC pages from there I can make a call to this action method smoothly without any error.

While making calls from classic ASP.NET pages, this shows error.

Reason:: Anti-forgery token is not embedded in ASP.NET pages it seems. 

can any one help me with the solution?

Upvotes: 0

Views: 2618

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039508

In order to generate the required hidden field containing the token you could use the AntiForgery.GetHtml static method:

<%@ Page Language="C#" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <%= AntiForgery.GetHtml() %>
        <asp:LinkButton 
            runat="server" 
            ID="btn" 
            PostBackUrl="~/SomeController/AddMenuFavorite/123" 
            Text="Go to the MVC site" 
        />
    </div>
    </form>
</body>
</html>

And since your action returns JSON I suspect that you are calling it using an AJAX request. In this case you can use the value of the hidden field generated by the helper to send it along with the AJAX request:

$(function() {
    $('#someLink').click(function() {
        $.post(this.href, $('form').serialize(), function(result) {
            // do something with the result
        });
        return false;
    });
});

Upvotes: 3

Related Questions