asp.net-core - 对预检请求的响应未通过访问控制检查 : It does not have HTTP ok status. GET 工作 POST PUT DELETE 不工作

标签 asp.net-core cors asp.net-core-webapi angular8 preflight

问候

我有一个具有以下架构的 Web 应用程序: Web api:ASP.net core 2.1(Windows 身份验证) 用户界面:角度8

UI 能够获取数据但无法发送数据。 我的意思是 GET 方法工作正常,但 POST、PUT、DELETE 选项不起作用。 所有方法都可以使用 POSTMAN 来工作。

错误是: 访问位于“http://xx.xxx.xxx.xx:xxyy/xxx/xxxxxx/Method”的 XMLHttpRequest '来自原点'http://localhost:xxxx ' 已被 CORS 策略阻止: 对预检请求的响应未通过访问控制检查:它没有 HTTP 正常状态。

任何帮助将不胜感激。

提前致谢:)

最佳答案

这就是我使用的,我希望它应该适用于您的情况。

我的startup.csConfigureServices()装饰有:

services.AddCors(feature =>
                feature.AddPolicy(
                    "CorsPolicy",
                    apiPolicy => apiPolicy
                                    //.AllowAnyOrigin()
                                    //.WithOrigins("http://localhost:4200")
                                    .AllowAnyHeader()
                                    .AllowAnyMethod()
                                    .SetIsOriginAllowed(host => true)
                                    .AllowCredentials()
                                ));

并且,Configure() 方法具有:

app.UseCors("CorsPolicy");

注意 SetIsOriginAllowed() 和 allowedCreds() 以及其他策略设置,这对我来说适用于从我的角度对我的 api 进行 POST 调用,这些调用在两个不同的端口号上运行。

更新:

根据评论中的问题,添加有关如何检查登录用户(Windows 身份验证)btwn api 和 Angular(前端)的附加信息。

您可以检查特定路由上的传入用户,该路由仅期望使用装饰 [Authorize] 进行身份验证的用户。就我而言,我只有一种方法需要 Windows 用户在 api 中:

[HttpGet("UserInfo")]
[Authorize]
public IActionResult GetUserInfo()
{
    string defaultCxtUser = HttpContext?.User?.Identity?.Name;

    if (defaultCxtUser != null && !string.IsNullOrEmpty(defaultCxtUser))
    {
        _logger.LogDebug($"START - Get Context user details for {defaultCxtUser}");
        ADHelper.logger = _logger;
        var userFullName = ADHelper.GetUserIdentityInfo(defaultCxtUser);
        _logger.LogInformation($"Context user {defaultCxtUser} with name: {userFullName}");
        var userInfo = new { Name = userFullName };
        //_logger.LogDebug($"END - GetUserInfo({defaultCxtUser} for {userFullName}");
        return Ok(userInfo);
    }
    else
        return Ok(new { Name = defaultCxtUser });
}

然后我会从我的角度将其称为服务调用,

// Get the Logged in user info
GetCurrentUserInfo(): Observable<string> {
const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json'
  }),
  withCredentials: true
 };

// return this.http.get<string>(`${ApiPath}UserInfo`, httpOptions)
// .pipe(map(v => v as string));
return this.http.get<UserInfo>(`${ApiPath}UserInfo`, httpOptions)
.pipe(map(data => {
  // console.log(data, data.Name);
  return data.Name;
}))
;
}

请参阅带有“withCredentials: true”行的 header ,该行将触发传递当前用户信息,并且只有在 C# 端具有读取 User.Identity 对象的授权 attr 时才会读取和理解它。我们在特定方法上执行此操作的原因是,api 中应该有一些其他父方法,例如 ApiStatus() 或任何可能的方法,应该首先调用。这将确保还使用需要匿名身份验证的选项来调用预检检查。就像我的例子一样,在从我的角度应用程序获取 userInfo() 之前,先获取 api 是否可用并正在运行,以及其他一些应用程序环境信息。

关于asp.net-core - 对预检请求的响应未通过访问控制检查 : It does not have HTTP ok status. GET 工作 POST PUT DELETE 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60374968/

相关文章:

asp.net-mvc - ASP.Net Core MVC 依赖注入(inject)不起作用

c# - 在 .Net Core AppSettings/配置中处理带句点的键名

aws-lambda - 如何为 apollo-server-lambda 启用 cors

javascript - 尽管启用了 CORS,$http Angular 仍无法工作

c# - 如何在我的应用程序中使用基本身份验证?

c# - 网络核心 : Convert String to TagBuilder

c# - 从 Visual Studio 启动 ASP.NET Core 不是从构建文件夹启动

javascript - $.support.cors 澄清吗?

c# - 将 google 身份验证添加到 **现有** .net core 2 web api 项目

asp.net-core-2.0 - ASP.NET Core 2.0中间件-访问配置设置