18

Actually this is not a duplication post,I know a part of the title asked many times in stackoverflow community, I read all posts, and answers, but I think my problem and technologies which I used are different.

First of all I should mention ASP.NET Core WEB/API is my back-end-app and Reactjs is my front Application.

I read about CORS and I found out I must enable CORS on ASP.NET App and put 'Access-Control-Allow-Origin':'*' on my request's header, but I still have the below error while I call an api:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 500. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

This is my Startup.cs code related to CORS:

public void ConfigureServices(IServiceCollection services)
{

    // other lines of code
    services.AddCors(options =>
    {
        options.AddPolicy("AllowAll",
            builder =>
            {
                builder
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader();
            });
    });

    services.Configure<MvcOptions>(options =>
    {
        options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAll"));
    });
    // other lines of code
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();
    app.UseCors("AllowAll");
    app.UseAuthentication();
    app.UseMvc();
}

This is my react code:

function save(message) {
    const requestOptions = {
        method: 'POST',
        mode: 'cors',
        headers: { ...authHeader(), 
            'Content-Type': 'application/json',    
            'Access-Control-Allow-Origin':'*',

    },
        body: JSON.stringify(message)               
    };
    return fetch(config.apiUrl + '/message/save', requestOptions).then(handleResponse, handleError);
}

Thanks for your responding.

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Siavash
  • 2,813
  • 4
  • 29
  • 42
  • 4
    *The response had HTTP status code **500*** is key here. When there's an exception in your ASP.NET Core project, the CORS headers are *cleared*. You should try and find out why an exception is being thrown. – Kirk Larkin Oct 19 '18 at 16:05
  • @sideshowbarker how can this be a dublicate if this question is about asp.net core and the older question is 5 years old and targeting a completely different framework (asp.net web api)? – Felix K. Oct 19 '18 at 18:35
  • 1
    by the way, makes no sense to put the Access-Control-Allow-Origin':'*' as your request header. it is set by the server in the response; see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin – Felix K. Oct 19 '18 at 18:40
  • @sideshowbarker "gotta wonder what problem adding Access-Control-Allow-Origin to a 500 error response would solve." → It makes much sense to include more details in the response payload of the response about the 500. But without CORS headers the client cannot open the payload. As linked in my response, the dotnet devs agreed on this and actually implemented [a fix](https://github.com/aspnet/AspNetCore/issues/2378#issuecomment-400094582). So no, the answers for different frameworks are not the same just because the problem is the same. please reopen. – Felix K. Oct 19 '18 at 19:00

4 Answers4

20

I had a similar problem recently. In my case it started working when I added services.AddCors(); in my ConfigureServices method and this part of code

app.UseCors(builder => builder
   .AllowAnyOrigin()
   .AllowAnyMethod()
   .AllowAnyHeader()
   .AllowCredentials());

in my Configure method. Remember to add those BEFORE UseMvc() call in both cases.

newbie
  • 210
  • 3
  • 6
9

After two difficult days finally I found out how can I fix my problem. Actually one of your comment was a nice clue for me.

@kirk-larkin said:

The response had HTTP status code 500 is key here. When there's an exception in your ASP.NET Core project, the CORS headers are cleared. You should try and find out why an exception is being thrown.

I traced my code many times, then i found out I forget to register a service which I used in my controller in Startup.cs.

I called these below code in Startup.cs and my problem solved.

services.AddScoped<IMessageService, MessageService>();
Siavash
  • 2,813
  • 4
  • 29
  • 42
  • 3
    I'm glad that comment was so helpful. It's so easy to get distracted here thinking that the problem is with CORS when the originating problem is actually an exception. – Kirk Larkin Oct 20 '18 at 14:27
  • 1
    Yes, the root of the problem is the underlying exception but that the response is lacking the "Access-Control-Allow-Origin" header is still a CORS problem!! And in newer versions of dotnet core, headers are also being sent on error (see my answer). – Felix K. Nov 10 '18 at 09:48
  • Thank you SO MUCH! – kovalyovi Dec 07 '20 at 23:10
  • Pashmaaaaaam, you saved my second day, Thanks! – Mojtaba Feb 17 '21 at 17:40
5

With ASP.NET Core 2.1, when the controller throws an exception, which results in an error 500, the CORS headers are not sent. This should be fixed in the next version but until then you could use a middleware to fix this.

see

Also note that with credentials you need to explicitly add WithOrigins with host and port since most browsers simply ignore it otherwise (see https://stackoverflow.com/a/19744754/2477619):

  app.UseCors(builder =>
    builder
      .WithOrigins("http://localhost:4200")
      .AllowAnyHeader()
      .AllowAnyMethod()
      .AllowCredentials()
  );
Felix K.
  • 14,171
  • 9
  • 58
  • 72
0

As said by @Siavash the fact that it is returning 500 may indicate there is an issue with the build. I was having this problem today as it was working fine on localhost but was failing when deployed.

To debug the error, find this line in your web.config file in the root of the IIS directory:

<aspNetCore processPath="dotnet" arguments=".\CarpetrightBackend.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />

Change stdoutLogEnabled="false" to true and then you will be able to see the error in the log file generated.

In my case I forgot to incude some static csv files when deploying that the program needed to reference and return data from it.

Fabio Mendes Soares
  • 1,357
  • 5
  • 20
  • 30