2

Empty web.api project, install Microsoft.aspnet.webapi.cors 5.2.3, add

config.EnableCors();

to webapiconfig. make controller and action

public class HomeController : ApiController
{
    [EnableCors("*" , "*" , "*")]
    public async Task<string> Get()
    {
        return await Task.FromResult("omg");
    }
}

Debug app and Load up fiddler and do a request to http://localhost:61939/api/Home

there are no CORS headers present. web.config contains:

<system.webServer>
<handlers>
  <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
  <remove name="OPTIONSVerbHandler" />
  <remove name="TRACEVerbHandler" />
  <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>

what am I missing? Why would this not insert an Access-Control-Allow-Origin header in all request to my Get method?

Also the answer of defining CORS in web.config isn't an answer ... At some point I will need to add origin checking and potentially even checking the HTTP Method something like:

if(requestContext.HttpMethod == "POST" && (origin == "https://someplace.com" || origin == "http://localhost"))
dev null
  • 165
  • 1
  • 14

1 Answers1

5

What you've done is enough to enable CORS, you can also enable CORS on all the controllers using this code :

 var cors = new EnableCorsAttribute("*", "*", "*"); 
 config.EnableCors(cors); 

I'm not sure how you're testing it, but note that only once the request contains the Origin header, it returns the Access-Control-Allow-Origin header in reponse. If you omit the origin header in the request, the response wouldn't contain the Access-Control-Allow-Origin.

Request and Response Headers

akardon
  • 43,164
  • 4
  • 34
  • 42
  • I'm not so sure I follow, i'm not using owin (app.UseCors) – dev null Jul 20 '16 at 01:16
  • Sorry I didn't notice it's not using pipelines .I've edited the answer, have another look – akardon Jul 20 '16 at 03:49
  • Your totally right that's all I was missing, thank you so much! – dev null Jul 20 '16 at 11:12
  • 1
    Wow, @akazemis .. your answer helped me solving my problem. I had the same case WebApi2 on IIS Express and not working only in Chrome and Firefox. What was wrong in my case was that I had a slash '/' on the end when configuring the allowed origin like http://localhost:xxxx/ .. So stupid by myself but it can happen to everybody. Hope that will help someone not having the struggle I had :D Have a nice day and thanks again! – Kalin Krastev Mar 14 '17 at 09:29