Blazor 无法连接到 ASP.NET Core WebApi (CORS)
Blazor cannot connect to ASP.NET Core WebApi (CORS)
我在本地 IP https://192.168.188.31:44302
上有一个 ASP.NET 核心服务器 运行,带有 Web API Enpoints。
我可以使用 VS Code REST Client 连接到所述服务器。
现在我想在 https://192.168.188.31:5555
.
上使用 Blazor WebAssembly 运行 连接到 Web API
我的 Blozor 代码:
@page "/login"
@inject HttpClient Http
[ ... some "HTML"-Code ... ]
@code {
private async Task Authenticate()
{
var loginModel = new LoginModel
{
Mail = "some@mail.com",
Password = "s3cr3T"
};
var requestMessage = new HttpRequestMessage()
{
Method = new HttpMethod("POST"),
RequestUri = ClientB.Classes.Uris.AuthenticateUser(),
Content =
JsonContent.Create(loginModel)
};
var response = await Http.SendAsync(requestMessage);
var responseStatusCode = response.StatusCode;
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("responseBody: " + responseBody);
}
public async void LoginSubmit(EditContext editContext)
{
await Authenticate();
Console.WriteLine("Debug: Valid Submit");
}
}
当我现在触发 LoginSubmit
时,我在 Chrome 和 Firefox 的开发人员控制台中收到以下错误消息:login:1 Access to fetch at 'https://192.168.188.31:44302/user/authenticate' from origin 'https://192.168.188.31:5555' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
我是 web 开发的新手,发现你必须在服务器端启用 CORS ASP.NET 核心项目,所以我用
扩展了 startup.cs
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<UserDataContext, UserSqliteDataContext>();
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("https://192.168.188.31:44302",
"https://192.168.188.31:5555",
"https://localhost:44302",
"https://localhost:5555")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
services.AddControllers();
services.AddApiVersioning(x =>
{
...
});
services.AddAuthentication(x =>
...
});
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
services.AddScoped<IViewerService, ViewerService>();
}
public void Configure(IApplicationBuilder app,
IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
Program.IsDevelopment = env.IsDevelopment();
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseCors(MyAllowSpecificOrigins);
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
Log.Initialize();
}
但我仍然收到上述错误信息。
我在配置 CORS 时做错了什么吗?
为什么它与 VS Code REST 客户端一起按预期工作以及我如何在 Blazor WASM 应用程序中调用错误?
导致错误消息 login:1 Access to fetch at 'https://192.168.188.31:44302/user/authenticate' from origin 'https://192.168.188.31:5555' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
的问题是由 HttpsRedirection
引起的。
要解决此问题,请通过删除函数 Configure
中的行 app.UseHttpsRedirection();
来停用 HttpsRedirection
,或者在函数 ConfigureServices
中添加用于重定向的正确端口(推荐方式).
在我的例子中,我在 44302
端口启动我的 WebAPI,所以我的解决方案如下所示(您必须根据您的端口号调整它):
if (Program.IsDevelopment)
{
services.AddHttpsRedirection(options =>
{
options.RedirectStatusCode = StatusCodes.Status308PermanentRedirect;
options.HttpsPort = 44302;
});
}
else
{
services.AddHttpsRedirection(options =>
{
options.RedirectStatusCode = StatusCodes.Status308PermanentRedirect;
options.HttpsPort = 443;
});
}
另请注意,将请求 API 的 IP 地址添加到 CORS 中就足够了:
services.AddCors(options =>
{
options.AddPolicy(name: specificOrigins,
builder =>
{
builder.WithOrigins("https://192.168.188.31:5555",
"http://192.168.188.31:5444")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
第 1 步:请在您的 WebAPI 中添加以下代码 Startup.cs 以允许具有特定来源的 CORS:
services.AddCors(options =>
{
options.AddDefaultPolicy(builder =>
builder.WithOrigins("https://localhost:44351")
.AllowAnyHeader()
.AllowAnyMethod());
});
第 2 步:现在将上面代码中的“https://localhost:44351”更改为您的 Blazor Web 程序集应用程序的 URL。请参考下面的屏幕截图:
第 3 步:现在在 app.UseRouting() 之后和 app.UseRouting() 之前在 WebAPI 的配置方法中添加 app.UseCors()。请参考以下屏幕截图:
我也遇到了同样的问题,它解决了我的问题。希望它也对你有用。
注意:无需更改 Blazor Web 程序集代码即可解决上述问题。
我在本地 IP https://192.168.188.31:44302
上有一个 ASP.NET 核心服务器 运行,带有 Web API Enpoints。
我可以使用 VS Code REST Client 连接到所述服务器。
现在我想在 https://192.168.188.31:5555
.
我的 Blozor 代码:
@page "/login"
@inject HttpClient Http
[ ... some "HTML"-Code ... ]
@code {
private async Task Authenticate()
{
var loginModel = new LoginModel
{
Mail = "some@mail.com",
Password = "s3cr3T"
};
var requestMessage = new HttpRequestMessage()
{
Method = new HttpMethod("POST"),
RequestUri = ClientB.Classes.Uris.AuthenticateUser(),
Content =
JsonContent.Create(loginModel)
};
var response = await Http.SendAsync(requestMessage);
var responseStatusCode = response.StatusCode;
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("responseBody: " + responseBody);
}
public async void LoginSubmit(EditContext editContext)
{
await Authenticate();
Console.WriteLine("Debug: Valid Submit");
}
}
当我现在触发 LoginSubmit
时,我在 Chrome 和 Firefox 的开发人员控制台中收到以下错误消息:login:1 Access to fetch at 'https://192.168.188.31:44302/user/authenticate' from origin 'https://192.168.188.31:5555' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
我是 web 开发的新手,发现你必须在服务器端启用 CORS ASP.NET 核心项目,所以我用
扩展了startup.cs
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<UserDataContext, UserSqliteDataContext>();
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("https://192.168.188.31:44302",
"https://192.168.188.31:5555",
"https://localhost:44302",
"https://localhost:5555")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
services.AddControllers();
services.AddApiVersioning(x =>
{
...
});
services.AddAuthentication(x =>
...
});
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
services.AddScoped<IViewerService, ViewerService>();
}
public void Configure(IApplicationBuilder app,
IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
Program.IsDevelopment = env.IsDevelopment();
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseCors(MyAllowSpecificOrigins);
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
Log.Initialize();
}
但我仍然收到上述错误信息。 我在配置 CORS 时做错了什么吗? 为什么它与 VS Code REST 客户端一起按预期工作以及我如何在 Blazor WASM 应用程序中调用错误?
导致错误消息 login:1 Access to fetch at 'https://192.168.188.31:44302/user/authenticate' from origin 'https://192.168.188.31:5555' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
的问题是由 HttpsRedirection
引起的。
要解决此问题,请通过删除函数 Configure
中的行 app.UseHttpsRedirection();
来停用 HttpsRedirection
,或者在函数 ConfigureServices
中添加用于重定向的正确端口(推荐方式).
在我的例子中,我在 44302
端口启动我的 WebAPI,所以我的解决方案如下所示(您必须根据您的端口号调整它):
if (Program.IsDevelopment)
{
services.AddHttpsRedirection(options =>
{
options.RedirectStatusCode = StatusCodes.Status308PermanentRedirect;
options.HttpsPort = 44302;
});
}
else
{
services.AddHttpsRedirection(options =>
{
options.RedirectStatusCode = StatusCodes.Status308PermanentRedirect;
options.HttpsPort = 443;
});
}
另请注意,将请求 API 的 IP 地址添加到 CORS 中就足够了:
services.AddCors(options =>
{
options.AddPolicy(name: specificOrigins,
builder =>
{
builder.WithOrigins("https://192.168.188.31:5555",
"http://192.168.188.31:5444")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
第 1 步:请在您的 WebAPI 中添加以下代码 Startup.cs 以允许具有特定来源的 CORS:
services.AddCors(options =>
{
options.AddDefaultPolicy(builder =>
builder.WithOrigins("https://localhost:44351")
.AllowAnyHeader()
.AllowAnyMethod());
});
第 2 步:现在将上面代码中的“https://localhost:44351”更改为您的 Blazor Web 程序集应用程序的 URL。请参考下面的屏幕截图:
第 3 步:现在在 app.UseRouting() 之后和 app.UseRouting() 之前在 WebAPI 的配置方法中添加 app.UseCors()。请参考以下屏幕截图:
我也遇到了同样的问题,它解决了我的问题。希望它也对你有用。
注意:无需更改 Blazor Web 程序集代码即可解决上述问题。