Web API 2 CORS IIS Express Debug and No Access-Control-Allow-Origin header

試著忘記壹切 提交于 2019-12-24 08:19:19

问题


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"))

回答1:


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.



来源:https://stackoverflow.com/questions/38470193/web-api-2-cors-iis-express-debug-and-no-access-control-allow-origin-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!