如何在.NET Core MVC中启用CORS

问题描述 投票:0回答:1

我在前端有一个简单的操作(=JavaScript),它返回一些 JSON。

这是代码示例:

function DiacritizeText() {
    var text = $("#Paragraph").val()
    var api_key = "Api_Key";
    var i;
    var settings = {
        "async": true,
        "crossDomain": true,
        "url": "https://farasa.qcri.org/webapi/segmentation/",
        "method": "POST",
        "headers": { "content-type": "application/json", "cache-control": "no-cache", },
        "processData": false,
        "data": "{\"text\":" + "\"" + text + "\", \"api_key\":" + "\"" + api_key + "\"}",
    }
    $.ajax(settings).done(function (response) {
        console.log(response);
        $("#Paragraph").text(JSON.parse(response).text);
    });
}

当我执行这个函数时,我得到了这些错误

从源 https://localhost:44377 访问“https://farasa.qcri.org/webapi/segmentation/”处的 XMLHttpRequest 已被 CORS 策略阻止:没有“Access-Control-Allow-Origin”标头存在于所请求的资源上。
发布 https://farasa.qcri.org/webapi/segmentation/ net::ERR_FAILED 400

我已经搜索了一些资源,大多数事情都规定处理应该在 API 上完成,但这是不可能的,因为 API 不在我们的网络中

我必须尝试从我这边启用脚趾 CORS

第一次尝试是在启动中添加 CORS

public class Startup
    {
        readonly string allowSpecificOrigins = "_allowSpecificOrigins";
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        
        services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
        {
            builder.WithOrigins("https://farasa.qcri.org/")
                   .AllowAnyMethod()
                   .AllowAnyHeader();
        }));

        var ConnectionString = Configuration.GetConnectionString("EducationSystemDBContextConnection");

        services.AddDbContext<EducationSystemDBContext>(options => options.UseSqlServer(ConnectionString));


        var mapperConfig = new MapperConfiguration(mc =>
        {
            mc.AddProfile(new MappingProfile());
        });

        IMapper mapper = mapperConfig.CreateMapper();
        services.AddSingleton(mapper);
        //services.AddAutoMapper(typeof(Startup));

        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie("Cookies", options =>
        {
            options.LoginPath = "/User/Login";
            options.LogoutPath = "/User/Logout";
            options.AccessDeniedPath = "/User/AccessDenied";
            options.ReturnUrlParameter = "ReturnUrl";
        });

        services.AddControllersWithViews();
        services.AddRazorPages();
    }

    // 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.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        //app.UseMvcWithDefaultRoute();
        app.UseRouting();
        app.UseCors("MyPolicy");
        
        app.UseCookiePolicy(new CookiePolicyOptions()
        {
            MinimumSameSitePolicy = SameSiteMode.Strict
        });

        app.UseAuthentication();
        app.UseAuthorization();
        
        //app.MapRazorPages();
        //app.MapDefaultControllerRoute();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
            endpoints.MapRazorPages();
        });

       
    }
}

第二次尝试:由于我在 ASP.Net Framework 中遇到了同样的问题,并且通过在 web.config 中添加

<customHeaders>
来修复它,我认为在 .NET core 中它可能会出现相同的情况。

所以我在核心 MVC Web 应用程序中添加了 web.config,然后添加了

<customHeaders>
如下

<system.webServer>
    <httpProtocol>
            <customHeaders>
            <add name="Access-Control-Allow-Origin" value="*" />
            <add name="Access-Control-Allow-Headers" value="Content-Type" />
            <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, OPTIONS" />
        </customHeaders>
    </httpProtocol>
</system.webServer>

那么,如何从 .NET Core MVC Web 应用程序处理 CORS?

c# .net-core asp.net-core-mvc cors
1个回答
0
投票
    public static void Register(HttpConfiguration config)
{
    var corsAttribute = new EnableCorsAttribute("http://example.com", "*", "*");
    config.EnableCors(corsAttrribute);
}

HttpContext.Response.AppendHeader("Access-Control-Allow-Origin", "*");

或者您可以将其添加到 wor web.config 文件中:

<system.webServer>

    <httpProtocol>

      <customHeaders>

        <clear />

        <add name="Access-Control-Allow-Origin" value="*" />

      </customHeaders>

    </httpProtocol>

如果您想为 Web api 启用 CORS,您需要将其添加到您的 Web Api 项目的 global.asax 文件夹中。

protected void Application_BeginRequest()
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
        }
© www.soinside.com 2019 - 2024. All rights reserved.