有多种方法可以实现此目的,可以在类似问题上找到其他答案 -->用于 PUT 和 POST 的 Angular4 ASP.NET Core 1.2 Windows 身份验证 CORS 给出 401 https://stackoverflow.com/questions/45108307/
跨域资源共享模块
可以使用以下命令来配置 IIS跨域资源共享模块 https://www.iis.net/downloads/microsoft/iis-cors-module.
正如这里所见:https://blogs.iis.net/iisteam/getting-started-with-the-iis-cors-module https://blogs.iis.net/iisteam/getting-started-with-the-iis-cors-module
此处提供更多信息:https://blogs.iis.net/iisteam/getting-started-with-the-iis-cors-module https://blogs.iis.net/iisteam/getting-started-with-the-iis-cors-module
IIS CORS 模块旨在处理 CORS 预检请求
在其他 IIS 模块处理相同请求之前。 OPTIONS 请求
始终是匿名的,因此 CORS 模块为 IIS 服务器提供了一种方法
即使匿名也能正确响应预检请求
需要在服务器上禁用身份验证。
您需要通过 Web Config 启用 CORS 模块:
<?xml version="1.0"?>
<configuration>
<system.webServer>
<cors enabled="true">
<add origin="*" allowCredentials="true" />
</cors>
</system.webServer>
</configuration>
为了更精细的控制:
<?xml version="1.0"?>
<configuration>
<system.webServer>
<cors enabled="true">
<add origin="https://readonlyservice.constoso.com" allowCredentials="true">
<allowMethods>
<add method="GET" />
<add method="HEAD" />
</allowMethods>
<allowHeaders>
<add header="content-type" />
<add header="accept" />
</allowHeaders>
</add>
<add origin="https://readwriteservice.constoso.com" allowCredentials="true">
<allowMethods>
<add method="GET" />
<add method="HEAD" />
<add method="POST" />
<add method="PUT" />
<add method="DELETE" />
</allowMethods>
</add>
</cors>
</system.webServer>
</configuration>
重定向选项
您可以重定向所有 OPTIONS 请求以始终给出 OK 状态。
然而,这将颠覆预检请求的整个概念,因此仅当它适用于您的情况时才使用它。
安装重定向模块 https://learn.microsoft.com/en-us/iis/configuration/system.webserver/httpredirect/#setup in IIS.
将以下重定向添加到您的 Web Config。
<rewrite>
<rules>
<rule name="CORS Preflight Anonymous Authentication" stopProcessing="true">
<match url=".*" />
<conditions>
<add input="{REQUEST_METHOD}" pattern="^OPTIONS$" />
</conditions>
<action type="CustomResponse" statusCode="200" statusReason="Preflight" statusDescription="Preflight" />
</rule>
</rules>
</rewrite>
中间件
或者,可以通过在 IIS 中启用匿名身份验证并在 Net Core API 中创建一个中间件来检查人员是否经过正确身份验证来实现所需的结果。
中间件:
public AuthorizationMiddleware(RequestDelegate next, ILogger logger)
{
_next = next;
_log = logger;
}
public async Task Invoke(HttpContext httpContext)
{
//Allow OPTIONS requests to be anonymous
if (httpContext.Request.Method != "OPTIONS" && !httpContext.User.Identity.IsAuthenticated)
{
httpContext.Response.StatusCode = 401;
await httpContext.Response.WriteAsync("Not Authenticated");
}
await _next(httpContext);
}