Allowing for Cross Origin Resource Sharing

For security purposes, .Net will prevent web pages from posting a form to a different domain and page. Sometimes, you want to do this, though, for development or for centralizing code.

-Sean J. Miller 7/2/2022

Cross Origin Resource Sharing (CORS) provides browsers a way to request remote URLs only when they have permission.  Razor Pages by default will prevent a Form that originated somewhere else from posting to the page handler.  However, sometimes you might want to do that.  

Troubleshooting package integration was my reason.  I wanted to test out TinyMCE's upload image feature.  It has its own uploader that you provide your endpoint to.  Unfortunately, it doesn't bring in any other form fields when it posts, so the AntiforgeryToken automatically placed by ASP.Net isn't included with the post.  I tried the custom upload code option, but still couldn't get it to land.  I spent several hours beating my head against the keyboard trying to get it to return anything but "Bad Request".  I finally thought to disable the AntiForgery and, poof, it worked.

Here is a snippet:

namespace raw.Pages
    [IgnoreAntiforgeryToken(Order = 1001)]
    public class EditModel : PageModel

The magic part is, of course, IgnoreAntiforgeryToken.  So, the next time you are having trouble getting yoru jQuery AJAX to successfully post to your .Net code, give this a try.  Placing it at the page model will have it affect solely that page - not your entire site.

Have a question?
Back to Home