1

I am trying to POST an object from my Angular app to an ASP.NET WebApi but I get the following error.

Failed to load http://localhost:64859/api/comments: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 404. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

In the .service.ts, I am sending a POST with fetch().

fetch(this.Url, {
  method: 'post',
  body: JSON.stringify(obj), 
  headers:{
    'Content-Type': 'application/json'
    'Access-Control-Allow-Origin': '*' // Do I need this?
  } 
}).then(function (response) {
  console.log(response.text());
  return response.json();
}).then(function(data) {
  console.log('Error:', data);
});

This is the controller in my API.

// POST api/<controller>
[HttpPost]
[EnableCors(origins: "*", headers: "*", methods: "*")]
public string Post([FromBody]Obj obj)
{ ... }

In Startup.cs...

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddCors(options =>
    {
        options.AddPolicy("AllowAllOrigins",
            builder => { builder.AllowAnyOrigin(); });
    });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    app.UseMvc();
}

1 Answer 1

1

I guess You have to put "AddCors" or "UseCors" before "AddMvc" / "UseMvc" something like this:

services.AddCors(o => o.AddPolicy("AllowAllOrigins", builder =>
            {
                 builder.AllowAnyMethod()
                   .AllowAnyHeader()
                   .AllowAnyOrigin();
            }));
services.AddMvc();

or in Configure method

app.UseCors("AllowAllOrigins");
app.UseMvc();

and change this part

[EnableCors(origins: "*", headers: "*", methods: "*")]

to

[EnableCors("AllowAllOrigins")]

and don't set "Access-Control-Allow-Origin" in fetch

try this and tell me the result

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.