0

I am having problems getting ASPNET CORE to receive json requests posted cross-domain from an AngularX client. I've looked around quite extensively but I am unable to find a question/solution to this specific variation of problem.

I set up CORS on the server and the requests are coming through to the server side, but the controller action's parameter consists only of null values. I read somewhere that I have to decorate the parameter with [FromBody], but when I do that the server returns a 415 Unsupported Media error to my AngularX client - but not to my Chrome PostMan plugin and not to

Here is how I enable CORS on my server side

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        app.UseMvc();
        app.UseCors("SiteCorsPolicy");
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        var corsBuilder = new CorsPolicyBuilder();
        corsBuilder.AllowAnyHeader();
        corsBuilder.AllowCredentials();
        corsBuilder.AllowAnyMethod();
        corsBuilder.AllowAnyOrigin(); 
        CorsPolicy corsPolicy = corsBuilder.Build();

        services.AddCors(x => x.AddPolicy("SiteCorsPolicy", corsPolicy));
    }

My controller code looks like this

public class ValuesController : Controller
{
    [HttpPost, Route("api/values/petes-test/")]
    public async Task<PetesTestResponse> List([FromBody]PetesTestQuery query)
    {
        var result = await ............;
        return result;
    }
}

And my client-side code looks like this

const headers = new Headers({
  'Content-Type': 'application/json; charset=utf-8',
  'Accept': 'application/json'
});

return this.http.post(url, JSON.stringify(request), { headers: headers })
  .map((res: Response) => <TResponse>res.json());

}

The headers from the client to the server are as follows

Request URL:http://localhost:4201/api/values/petes-test/
Request Method:OPTIONS
Status Code:415 Unsupported Media Type
Remote Address:[::1]:4201
Referrer Policy:no-referrer-when-downgrade
Accept:*/*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:en-GB,en-US;q=0.8,en;q=0.6
Access-Control-Request-Headers:content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:localhost:4201
Origin:http://localhost:4200
Referer:http://localhost:4200/
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
Peter Morris
  • 13,426
  • 8
  • 61
  • 112
  • check this link may be you get answer: https://stackoverflow.com/questions/44151963/cors-with-mvc5-webapi-and-angular-js/44152219#44152219 – Umapathi Jun 15 '17 at 09:57
  • Your browser will automatically calls options method before calling the real post request. this is due to you're making requests from different origins. All you have to do is just implement an options request in your controller, and in the response add the supported requests like, get,post etc check this link .https://stackoverflow.com/questions/29954037/how-to-disable-options-request – Anto Antony Jun 15 '17 at 10:39

1 Answers1

4

The order of how middlewares are added in the Configure method defines the order how these middlewares are invoked on requests. In your case the CORS middleware is defined after the MVC middleware what means the MVC middleware handles request first. Then MVC middleware matches the route so it makes the conclusion to not forward your request to the next middleware and after trying to deliver OPTIONS request to POST action it fails and returns 415 HTTP status code. Place the UseCors before UseMvc like shown below

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseCors("SiteCorsPolicy");
    app.UseMvc();
}
Alexey Andrushkevich
  • 5,299
  • 1
  • 30
  • 46