为了账号安全,请及时绑定邮箱和手机立即绑定

如何在ASP.net Core WebAPI中启用CORS

如何在ASP.net Core WebAPI中启用CORS

蝴蝶刀刀 2019-10-24 14:14:44
我要做什么我有一个在Azure免费计划上托管的后端ASP.Net Core Web API(源代码:https : //github.com/killerrin/Portfolio-Backend)。我也有一个客户网站,我想使用该API。客户端应用程序不会托管在Azure上,而是托管在Github Pages或我有权访问的另一个Web托管服务上。因此,域名将无法排列。考虑到这一点,我需要在Web API端启用CORS,但是现在我已经尝试了几乎所有内容几个小时,并且它拒绝工作。我如何进行客户端设置 它只是一个用React.js编写的简单客户端。我正在通过Jquery中的AJAX调用API。React站点可以正常工作,所以我不知道。正如我在尝试1中确认的那样,对Jquery API的调用有效。这是我进行调用的方式    var apiUrl = "http://andrewgodfroyportfolioapi.azurewebsites.net/api/Authentication";    //alert(username + "|" + password + "|" + apiUrl);    $.ajax({        url: apiUrl,        type: "POST",        data: {            username: username,            password: password        },        contentType: "application/json; charset=utf-8",        dataType: "json",        success: function (response) {            var authenticatedUser = JSON.parse(response);            //alert("Data Loaded: " + authenticatedUser);            if (onComplete != null) {                onComplete(authenticatedUser);            }        },        error: function (xhr, status, error) {            //alert(xhr.responseText);            if (onComplete != null) {                onComplete(xhr.responseText);            }        }    });
查看完整描述

3 回答

?
LEATH

TA贡献1936条经验 获得超6个赞

在ConfigureServices中添加  services.AddCors(); BEFORE services.AddMvc();。

在配置中添加UseCors


app.UseCors(builder => builder

    .AllowAnyOrigin()

    .AllowAnyMethod()

    .AllowAnyHeader()

    .AllowCredentials());   

app.UseMvc();

要点是app.UseCors在之前添加app.UseMvc()。


确保在MVC之前声明CORS功能,以便在MVC管道获得控制并终止请求之前触发中间件。


完成上述方法后,您可以对其进行更改,将其配置为特定的起源以接受api调用,并避免让您的API向任何人开放


public void ConfigureServices(IServiceCollection services)

{

    services.AddCors(options => options.AddPolicy("ApiCorsPolicy", builder =>

    {

        builder.WithOrigins("http://localhost:4200").AllowAnyMethod().AllowAnyHeader();

    }));

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

}

在configure方法中,告诉CORS使用您刚创建的策略:


app.UseCors("ApiCorsPolicy");

app.UseMvc();

我刚刚找到了该主题的紧凑文章-https: //dzone.com/articles/cors-in-net-core-net-core-security-part-vi


查看完整回答
反对 回复 2019-10-24
  • 3 回答
  • 0 关注
  • 972 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信