Cannot post JSON to ASPNET Core via CORS (415 - Unsupported media type)

时间:2017-06-15 09:53:40

标签: angular asp.net-web-api asp.net-core cors

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

1 个答案:

答案 0 :(得分:4)

Configure方法中添加中间件的顺序定义了如何在请求中调用这些中间件的顺序。在你的情况下,CORS中间件是在MVC中间件之后定义的,这意味着MVC中间件首先处理请求。然后MVC中间件匹配路由,因此它得出的结论是不将您的请求转发到下一个中​​间件,并且在尝试向OPTIONS操作发送POST请求后,它将失败并返回415 HTTP状态代码。将UseCors放在UseMvc之前,如下所示

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