gpt4 book ai didi

使用 CORS 在 IIS 上运行的 Angular 2 和 .net 核心 Web 应用程序之间的 HTTP 415 OPTIONS 请求

转载 作者:太空狗 更新时间:2023-10-29 18:31:39 24 4
gpt4 key购买 nike

我有一个在 IIS 中运行的 .net 核心 Web 应用程序 (api),它是从 Angular2 应用程序调用的。当我在 POST 调用上设置内容类型自定义 header 时,http 调用首先进行选项请求调用。 IIS(我假设)在选项调用中返回 415(不支持的媒体类型)。

我需要在 IIS(或 .net core)中的什么地方设置支持的媒体类型?

客户请求:

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"}

如果我将内容类型设置为 text/plain,那么我会返回 415 - 我是否需要在 IIS 或 .net core 中设置返回类型为 application/json?

在此先感谢社区!

最佳答案

好的,所以我的问题最终还是围绕着 CORS。我正在通过 IIS 设置 CORS header ,但在 .net core Startup 中设置它们解决了我的问题。不受支持的媒体类型响应代码让我失望了......

    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();
}

如果我可以让其他人省去一些挠头的事情,那就是快乐的日子!

关于使用 CORS 在 IIS 上运行的 Angular 2 和 .net 核心 Web 应用程序之间的 HTTP 415 OPTIONS 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42712803/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com