c# - 如何设置 ASP.NET CORS 选项以允许 application/json

标签 c# .net-core asp.net-web-api cors fetch

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

浏览器发送给我的错误是

MainPage.html:1 Access to fetch at 'https://localhost:44346/api/topic' from origin 'null' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response

我查看了几篇文章,发现我的问题是 WEB-API 中的 CORS 选项没有发回允许 application/json 的选项。据我了解,出现此问题的原因是我的浏览器和 ISS Express 在同一台计算机上,因此触发了 CORS。我一直在寻找资源来帮助我在 ASP.NET 中获取 CORS,以包含 application/json 作为允许的 header ,但没有取得任何进展。我还尝试在浏览器中禁用 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”部分的顶部。

关于c# - 如何设置 ASP.NET CORS 选项以允许 application/json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66199980/

相关文章:

.net-core - AWSRequestInfo.json 应该是什么样子?

c# - 配置文件 'appsettings.json'未找到且不可选

c# - 自定义 ASP.NET Web API 输出

c# - 为什么 Powershell 没有看到它已经加载了这个程序集?

c# - app.config 配置管理 - C#, .net

c# - 计算某些范围内的最大有理分数

c# - .net 核心中的 Nunit 并行属性

jquery - 无法使用 jquery 将参数从 body 传递到 webapi post 方法

angularjs - 从 WAAD 获取用户组的最简单方法是什么?

c# - 将 Action<T> 转换为 Action<object>