【发布时间】:2021-06-01 03:17:30
【问题描述】:
当我通过 Angular 10 前端将 httppost 和 httput(httpget 可以)制作到 API .net core 3.1 时遇到问题,控制台应用程序中的错误是著名的: 从源“http://localhost:4200”访问“http://localhost:23645/api/Toolbar/Search”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:否请求的资源上存在“Access-Control-Allow-Origin”标头。
这是我前面请求的代码:
constructor(private Http: HttpClient) {
this.header = new HttpHeaders(
{
'content-type': 'application/json'
}
)
searchToolbar(search: string): Observable<ToolbarSearchResultItem[]> {
return this.Http.post(this.url + '/myController/Search', { "search": search }, { headers: this.header, withCredentials:true}).pipe(tap((response: myTyoe[]) => {
return response;
}));
这是我在 Startup.cs 中的代码:
public void ConfigureServices(IServiceCollection services)
{
log.Info("ConfigureServices");
try
{
IConfigurationRoot configurationRoot = builder.Build();
services.AddCors(opt => opt.AddPolicy("CorsPolicy", c =>
{
c.WithOrigins("http://localhost:4200")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
}));
services.AddAuthorization(options =>
{
options.AddPolicy("AllUsers", policy => policy.RequireAuthenticatedUser());
});
services.AddControllers();
services.AddMvc();
}
catch (Exception ex)
{
log.Error("Error in ConfigureServices" + ex.Message + ex.StackTrace);
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
try
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseCors("CorsPolicy");
app.UseAuthorization();
在 launchSettings.json 我设置了这个:
"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": false,
"iisExpress": {
"applicationUrl": "http://localhost:23645",
"sslPort": 0
}
在 applicationhost.config 中:
<windowsAuthentication enabled="true">
<providers>
<add value="Negotiate" />
<add value="NTLM" />
</providers>
</windowsAuthentication>
这是我的控制器:
[HttpPost]
[Route("Search")]
[EnableCors("CorsPolicy")]
public IList<ToolbarSearchResultItem> Search(ToolbarSearch search)
{
//my code
}
这是控制台中的详细消息:请求 URL:http://localhost:23645/api/Toolbar/Search 请求方法:选项 状态码:401 未授权 远程地址:[::1]:23645 推荐人政策:strict-origin-when-cross-origin 缓存控制:私有 内容长度:6284 内容类型:文本/html;字符集=utf-8 日期:格林威治标准时间 2021 年 3 月 2 日星期二 15:52:05 服务器:Microsoft-IIS/10.0 WWW-认证:协商 WWW-认证:NTLM X-Powered-By: ASP.NET 接受:/ 接受编码:gzip、deflate、br 接受语言:fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7 访问控制请求标头:内容类型 访问控制请求方法:POST 连接:保持活动 主机:本地主机:23645 来源:http://localhost:4200 参考:http://localhost:4200/ Sec-Fetch-Dest:空 Sec-Fetch-Mode: cors Sec-Fetch-Site:同一站点
这是我的 web.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<location path="." inheritInChildApplications="false">
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath=".\MYEXE.exe" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
</system.webServer>
</location>
</configuration>
我认为这不是真正的 CORS 块问题,而是配置问题或其他问题,与这个问题非常相似:Trouble with CORS Policy and .NET Core 3.1 但我使用了探查器并且没有 SQL 问题
【问题讨论】:
-
您必须知道在 CORS 中间件之前发生的任何事情(例如,如果您的应用程序在授权中间件期间崩溃)生成的响应将没有 CORS 标头,因此它将显示为来自浏览器的角度。您应该查看 ASP.NET 生成的日志(可能在输出窗口中)。如果您删除“EnableCors”属性,操作是否正确?
-
在输出窗口中我没有错误,我尝试删除“EnableCors”属性并且我有同样的错误。
-
"ConnectionStrings": { "DefaultConnection": "data source=MyServer;initial catalog=DB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework;" , "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } },"AllowedHosts": "*"跨度>
-
从角度来看,您在 localhost:23645 上发送请求,但在 cors 中您使用的是 localhost:4200 。您需要使用相同的网址
-
localhost:4200 是 angular url,localhost:23645 是后端 url,Httpget 请求正常
标签: c# angular asp.net-core-webapi