Search code examples
c#asp.net.netwebformscors

How to allow CORS for ASP.NET WebForms endpoint?


I am trying to add some [WebMethod] annotated endpoint functions to a Webforms style web app (.aspx and .asmx).

I'd like to annotate those endpoints with [EnableCors] and thereby get all the good ajax-preflight functionality.

VS2013 accepts the annotation, but still the endpoints don't play nice with CORS. (They work fine when used same-origin but not cross-origin).

I can't even get them to function cross-origin with the down and dirty

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

approach -- my browsers reject the responses, and the cross-origin response headers don't appear.

How can I get CORS functionality in these [WebMethod] endpoints?


Solution

  • 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.