我在IIS中运行的.net核心网络应用程序(api)是从Angular2应用程序调用的。 http调用首先进行选项请求调用,因为我在POST调用中设置了内容类型自定义标头。 IIS(我假设)在选项调用上返回415(不支持的媒体类型)。
我在哪里需要在IIS(或.net核心)中设置支持的媒体类型?
客户请求:
let postparams = {
Action: 'DoStuff'
};
let body = JSON.stringify(postparams);
var headers = new Headers();
headers.append('Accept','application/json');
headers.append('Content-Type','application/json');
let options = new RequestOptions({headers: headers});
var url = 'http://localhost:9056/api/resolve';
var response = this.http.post(url, body, options).map(res => res.json());
Angular生成的fiddler的选项请求(返回415):
OPTIONS http://localhost:9056/api/resolve HTTP/1.1
Host: localhost:9056
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: http://localhost:8100
User-Agent: Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Mobile Safari/537.36
Access-Control-Request-Headers: content-type
Accept: */*
Referer: http://localhost:8100/
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: en-GB,en;q=0.8
在fiddler中有效的POST请求(返回200):
POST http://localhost:9056/api/resolve HTTP/1.1
Host: localhost:9056
Connection: keep-alive
Content-Length: 26
Origin: http://localhost:8100
User-Agent: Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Mobile Safari/537.36
content-type: application/json
Accept: */*
Referer: http://localhost:8100/
Accept-Encoding: gzip, deflate, br
Accept-Language: en-GB,en;q=0.8
{"Action":"DoStuff"}
如果我将content-type设置为text / plain,那么我会返回415 - 我需要在IIS或.net核心中设置返回类型是application / json吗?
先谢谢社区!
答案 0 :(得分:2)
好的,所以我的问题最终是围绕CORS。我是通过IIS设置CORS头,但在.net核心启动它启动解决了我的问题。不支持的媒体类型响应代码让我失望......
public void ConfigureServices(IServiceCollection services)
{
services.AddApplicationInsightsTelemetry(Configuration);
// Needed to add this section, and....
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
// ..... this line
app.UseCors("CorsPolicy");
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseApplicationInsightsRequestTelemetry();
app.UseApplicationInsightsExceptionTelemetry();
app.UseMvc();
}
如果我可以拯救别人,那么就会感到很伤心,然后快乐的日子!