1

I am developing .net Core Web Api with Vs Code with Angular 6, Vs Studio. The error is as follows; - Failed to load resource: the server responded with a status of 500 (Internal Server Error) - No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http: // localhost: 4200' is therefore not allowed access. The response was HTTP status code 500.

// I added to Startup.cs;
ConfigureServices === >>> services.AddCors ();
Configure === >>>> app.UseCors (bldr => bldr.WithOrigins ("http: // 
localhost: 4200") .WithMethods ("GET", "POST"). AllowAnyHeader ());

The problem is that; The problem is resolved in the get method, the data is retrieved but it does not work in the post method. Thanks in advance.

2
  • did you try ` app.UseCors(CorsOptions.AllowAll);` as @Anton suggested in the answer? Commented May 31, 2018 at 20:12
  • I tried but not Commented Jun 1, 2018 at 6:15

2 Answers 2

2

There are multiple ways to solve this, the dotnet core documentation talks about how to handle CORS.

This tends to be an issue only during development so this is my preferred method to solving this issue.

Add CORS rule to the services which allows everything during development

if (_env.IsDevelopment())
{
    services.AddCors(options =>
    {
        options.AddPolicy("AllowAll",
                  p => p.AllowAnyOrigin()
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .AllowCredentials());
    });
}

Then add the created rule to the Application Builder:

if (_env.IsDevelopment())
{
    app.UseCors("AllowAll");
}

Alternatevely

There is also a CORS browser extension available for Google Chrome, I am not sure about other browsers.

This is my goto when I don't want to meddle with the request/response headers and is a quick fix for when this issue occurs with other projects not just .net core.

A word of warning though, sometimes this plugin doesn't work.

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

1 Comment

I tried but not. ANGULAR; let headers = new Headers({ 'Content-Type': 'application/json' }); let options = new RequestOptions({ headers: headers }); options.responseType = ResponseContentType.Blob; let body = JSON.stringify(sorguParametreleri); return this.http.post(this.apiURL + "/AGranter/DownloadReport", body, options).map((response: any) => {
0

It's important to remember that services.AddCors() must come before services.AddMvc() and the same with app.UseCors() and app.UseMvc().

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.