How to allow CORS for ASP.NET WebForms endpoint? How to allow CORS for ASP.NET WebForms endpoint? asp.net asp.net

How to allow CORS for ASP.NET WebForms endpoint?


I recommend double-checking you have performed all steps on this page: CORS on ASP.NET

In addition to:

Response.AppendHeader("Access-Control-Allow-Origin", "*");

Also try:

Response.AppendHeader("Access-Control-Allow-Methods","*");

Try adding directly in web config:

<system.webServer>   <httpProtocol>     <customHeaders>       <add name="Access-Control-Allow-Methods" value="*" />       <add name="Access-Control-Allow-Headers" value="Content-Type" />     </customHeaders>   </httpProtocol></system.webServer>

Failing that, you need to ensure you have control over both domains.


If you need the preflight request, e.g. so you can send authenticated requests, you are not able to set Access-Control-Allow-Origin: *. It must be a specific Origin domain.
Also you must set the Access-Control-Allow-Methods and Access-Control-Allow-Headers response headers, if you are using anything besides the defaults.
(Note these constraints are just how CORS itself works - this is how it is defined.)

So, it's not enough to just throw on the [EnableCors] attribute, you have to set values to the parameters:

[EnableCors(origins: "https://www.olliejones.com", headers: "X-Custom-Header", methods: "PUT", SupportsCredentials = true)]

Or if you want to do things manually and explicitly:

HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Origin", "https://www.olliejones.com");HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Headers", "X-Custom-Header");HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Methods", "PUT");HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Credentials", "true");

One last thing - you do have to call .EnableCors() on initiation. In e.g. MVC or WebAPI, you would call this on HttpConfiguration, when registering the config and such - however I have no idea how it works with WebForms.


If you use the AppendHeader method to send cache-specific headers and at the same time use the cache object model (Cache) to set cache policy, HTTP response headers that pertain to caching might be deleted when the cache object model is used. This behavior enables ASP.NET to maintain the most restrictive settings. For example, consider a page that includes user controls. If those controls have conflicting cache policies, the most restrictive cache policy will be used. If one user control sets the header "Cache-Control: Public" and another user control sets the more restrictive header "Cache-Control: Private" via calls to SetCacheability, then the "Cache-Control: Private" header will be sent with the response.

You can create a httpProtocol in web config for customHeaders.

<httpProtocol>     <customHeaders>       <add name="Access-Control-Allow-Methods" values="*" />             </customHeaders>   <httpProtocol>