【问题标题】:CORS not working in ASP.NET core Web API projectCORS 在 ASP.NET 核心 Web API 项目中不起作用
【发布时间】:2020-11-01 12:47:58
【问题描述】:

我构建了一个 ASP.NET core Web API(net core 3.1),我尝试启用 CORS,但它似乎不起作用。

Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("AllowMyOrigin",
        builder =>
        {
            builder.SetIsOriginAllowed(t => true)
            .AllowCredentials();
        });
    });
    ...
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    //app.UseHttpsRedirection();


    app.UseRouting();

    app.UseCors("AllowMyOrigin");

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
    app.UseHttpsRedirection();
}

控制器:

[Route("api/[controller]")] 
[ApiController]
public class airdata_updateController : ControllerBase
{
    [EnableCors("AllowMyOrigin")]
    [HttpGet]
    public string test()
    {
        return "ok";
    }

    ...
}

我使用 Postman 在本地计算机上测试我的 API,它运行良好: local computer

但是我在同一局域网中的其他计算机上使用 Postman 来调用我的 API,它失败了: other computer

我该怎么办?

【问题讨论】:

标签: c# asp.net-core asp.net-core-webapi


【解决方案1】:

试试这个:

    public void ConfigureServices(IServiceCollection services)
    {
        ...
        
         services.AddCors();

        ...
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
       ...
       
        app.UseCors(
            options => options.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()
        );

       ...
    }

您的控制器方法中不需要任何装饰器,所有这些都应用了指定的 CORS 策略(AllowAnyOrigin、AllowAnyHeader、AllowAnyMethod)。如需自定义策略,请查看https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1

【讨论】:

  • 感谢您的回复!我试过了,但 CORS 仍然无法正常工作。
【解决方案2】:

也许这个选项可以帮助你。

services.AddCors(options =>
            {
                options.AddPolicy("AllowMyOrigin",
                    builder => builder
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowAnyOrigin()

                );
            });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-06
    • 1970-01-01
    • 2017-08-25
    • 2021-06-25
    • 2017-08-05
    • 2022-01-27
    • 2019-05-25
    相关资源
    最近更新 更多