MVC: Generating an AntiForgeryToken for a AJAX res

2019-07-18 10:32发布

I've spent a good few hours tonight trying to work this one out. Basically I have a form in MVC with an AntiForgeryToken so when I post back everything is validated and it's all good. The problem is that I have a JSON result method that generates a load of markup and returns HTML to the user. I am regenerating forms to return to the user in an ajax way, so I need to put the token into the HTML I return to the client otherwise when they POST back again the antiforgery stuff will still work.

So the essence of my problem is how would I access the token in order to put it in my dynamically generated html server side and how would I generate the matching cookie and then send it all back in the response to the user? Can't seem to find anything on google about this but people must be doing it. Help would be very much appreciated as my brain is starting to shutdown! Thanks This is the form

<form action="/DoSomething" method="post">
    <input name="__RequestVerificationToken" type="hidden" value="saTFWpkKN0BYazFtN6c4YbZAmsEwG0srqlUqqloi/fVgeV2ciIFVmelvzwRZpArs" />
    <!-- rest of form goes here -->
</form>

So in my controller i am building tis form with a stringbuilder to send back to the client in a JSON result but i need to be able to add the value for the __RequestVerificationToken to the input so that my security will still work

0条回答
登录 后发表回答