You ever run into an issue with your code, spend way to long looking at it and not get anywhere? Especially one that you’ve solved before but having a lapse in memory. That was me all too recently. I was setting up an app that consisted of three projects in a solution. One project for the API, one for the DTO, and another for the MVC. The problem with this setup is that any Javascript call from the MVC project to the API will be blocked when the data comes back due to the browser enforcing same-origin policy. Microsoft has a great write-up on how to Enable CORS within an ASP.NET Web API 2 project. For your own sanity please make sure you go the whole through section. I mean, the whole thing, all the way to the end, because at the end of the section is a rather important fact. When you are defining the EnableCors
attribute on the API controller you need to make sure that the forward slash at the end of the origins
parameter is removed.
Good: [EnableCors(origins: "http://localhost:49332", headers:"*", methods:"*")]
Bad: [EnableCors(origins: "http://localhost:49332/", headers:"*", methods:"*")]
That is it. That single forward slash tripped me up. The error written to the web DevTools console was
Access to XMLHttpRequest at 'http://localhost:49342/api/users/name/smith/' from origin 'http://localhost:49332' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Hope this helps you waste a little less time.