0

I have an .net core api controller setup and have used enabled cors as follows in the startup class:

In my configureServices function I've done the following:

service.AddCors(c =>
{
    c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
{

And in my configure function I've done: app.useCors();

On my client app I'm doing the following:

fetch(url, {
method: 'POST',
body: JSON.stringify(data),
headers: new Headers({
    'Content-Type': 'application/json'
}).then.....

When I make my call from the client I get the following error:

Access to fetch at 'http://...' from origin 'http://...' has been blocked by CORS policy: response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves you needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

My api post works using postman.

How can I get this to work from my client?

mo_maat
  • 2,110
  • 12
  • 44
  • 72
  • Not an answer, but I was reading [this link](https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1). At the bottom it says "When deploying to IIS, CORS has to run before Windows Authentication " Have you taken care of that? I'm no expert, just thought it was something to check. – user2740650 Mar 20 '20 at 03:33
  • I'm not using any authentication on my api. I'm running it through visual studio so iis express. – mo_maat Mar 20 '20 at 03:37

1 Answers1

0

You can configure CORS globally in WebApiConfig Register method for all APIs as follows

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        var cors = new EnableCorsAttribute("www.example.com", "*", "*");
        config.EnableCors(cors);
        // ...
    }
}

Or at an API Controller level, decorate it with EnableCors attribute as follows

[EnableCors(origins: "http://www.example.com", headers: "*", methods: "get,post")]
public class TestController : ApiController
{
    public HttpResponseMessage Get() { ... }
    public HttpResponseMessage Post() { ... }
    public HttpResponseMessage Put() { ... }    
}

For more details, follow Enable cross-origin requests in ASP.NET Web API 2

  • I'm using .net core 3.1. I'll try though. – mo_maat Mar 20 '20 at 03:39
  • If you are using ASP.NET core 3.1, Please follow this link https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1 – Raju Dasupally Mar 20 '20 at 03:47
  • I had used that earlier and had made progress but then I got another error: `415 (Unsupported media type)`. Now I need to figure that out. – mo_maat Mar 20 '20 at 03:55
  • Looks like the error 415 is subject to content type or encoding https://stackoverflow.com/questions/22566433/http-415-unsupported-media-type-error-with-json/51435417 – Raju Dasupally Mar 20 '20 at 04:12