【问题标题】:How to set ASP.NET CORS OPTION to allow application/json如何设置 ASP.NET CORS OPTION 以允许应用程序/json
【发布时间】:2021-05-17 20:45:06
【问题描述】:

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

浏览器发送给我的错误是

MainPage.html:1 CORS 策略已阻止从源“null”访问“https://localhost:44346/api/topic”获取:访问控制不允许请求标头字段内容类型- 预检响应中的允许标头

我查看了几篇文章,发现我的问题是我的 WEB-API 中的 CORS 选项没有发回允许 application/json 的选项。据我了解,发生此问题的原因是因为我的浏览器和 ISS Express 在同一台机器上,因此触发了 CORS。我一直在寻找资源来帮助我在 ASP.NET 中获取 CORS,以将 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();
            });
        }
    }
}

【问题讨论】:

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


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-22
      • 1970-01-01
      • 1970-01-01
      • 2019-05-28
      • 2021-10-23
      • 1970-01-01
      • 2020-11-21
      • 2016-06-08
      相关资源
      最近更新 更多