如何设置ASP.NET CORS选项允许application/json



如下面的代码所示,我正在向使用ASP.NET创建的web api发送一个post请求。服务器是ISS Express。

浏览器发送给我的错误是

MainPage.html:1从原点'null'获取'https://localhost:44346/api/topic'的访问已被CORS策略阻止:请求报头字段内容类型不允许在预飞行响应中的Access- control - allow - headers

我看了几篇文章,发现我的问题是我的WEB-API中的CORS选项没有返回一个选项,说允许application/json。据我所知,这个问题发生的原因是因为我的浏览器和ISS Express在同一台机器上,所以CORS被触发。我已经寻找资源来帮助我在ASP中获得CORS。. NET包含application/json作为一个被允许的头球,并没有取得任何进展。我也尝试在浏览器中禁用CORS,但我找不到一个网页来解释如何做到这一点。

我需要做什么来解决这个问题?

<标题>JavaScript代码
function SubmitTopic() 
{
//Boilerplate code erased for succinctness
console.log("Creating Request")
const request = new Request("https://localhost:44346/api/topic", {
method: 'POST',
body: json,
headers: {
'Content-Type': 'application/json'
}
});
console.log(request)
console.log("Starting POST request to API")
fetch(request).then(res => {
if (res.status == 201) {
console.log("Successfully added json")
console.log("Clearing name and description boxes")
name.value = "";
description.value = "";
}
else {
console.error("A problem has occured")
alert("Failed to post")
}
})
}

c# -启动代码

using DSPWHU.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Cors;
namespace DSPWHU
{
public class Startup
{
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<EvidenceContext>(opt => opt.UseSqlite("EvidenceList"));
services.AddDbContext<TopicContext>(opt => opt.UseSqlite("TopicList"));

services.AddControllers();
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.AllowAnyOrigin();
});
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors(MyAllowSpecificOrigins);
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}

尝试将service.AddCors()替换为:


services.AddCors(o => o.AddPolicy(MyAllowSpecificOrigins, builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));

并将其放在ConfigureServices部分的顶部。

相关内容