首页 > 解决方案 > 使用 Windows 身份验证的 Web api 中的 Cors 问题

问题描述

我正在尝试在 Web API 应用程序中启用 CORS 支持。在我的WebApiConfig.cs文件中,我有以下代码:

var cors = new EnableCorsAttribute(origins: "http://localhost:19509",
                                               headers: "*",
                                               methods: "*");
config.EnableCors(cors);

然而,这并没有奏效。我已经尝试了以下链接中的所有建议,但它们也不起作用:

我创建了一个没有授权/身份验证/安全实现的空项目,并尝试从我的前端点击这个空项目,并且成功了。基于此,我相信前端实现是没问题的。

是否有可能导致此问题的特定软件包,或者我需要更改的其他任何内容?

当我尝试使用禁用 cors 的 Chrome 浏览器时,它会运行。

//在 StartUp.cs 文件中实现 CORS 后更新问题。

我也尝试在 StartUp.cs 文件中应用 cors,但没有运气。下面是我在 StartUp.cs 文件中的代码。

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Abstractions;
using Microsoft.Owin;
using Owin;
using System.Web.Services;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.AspNetCore.Cors;

namespace xyz
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
        }
    }
}

标签: .netcors

解决方案


  1. 您可能应该将https://.

  2. 您可能应该从启动配置 cors。

  3. 您可能需要将 cors 配置为 AllowCredentials

    options.AddPolicy("Default", builder =>
    {
       builder.WithOrigins("http://localhost:19509")
            .WithOrigins("https://localhost:19509")
            .AllowCredentials()
            .AllowAnyHeader()
            .AllowAnyMethod();
    });
    

然后您需要将 cors 策略添加到应用程序,以便将其应用于每个请求

public void Configure(IApplicationBuilder app)
{
    app.UseCors("Default");
}

在开发阶段的附带说明中,您可以打开 cors 政策并在您学习时慢慢开始限制它。

编辑

“当我尝试使用禁用了 cors 的 Chrome 浏览器时,它就会运行。”

浏览器是强制执行 cors 的浏览器。如果它只在 cors 被禁用时运行,这意味着 cors 标头正在从服务器正确添加。

听起来您的问题是客户。听起来您要么尝试从客户端拨打电话,域不同于 localhost:19509,要么在登录过程中的某个时刻,您正在使用更新示例中未配置的 Https。


推荐阅读