gpt4 book ai didi

c# - Blazor 无法连接到 ASP.NET Core WebApi (CORS)

转载 作者:行者123 更新时间:2023-12-04 16:39:59 24 4
gpt4 key购买 nike

我有一个在本地 IP 上运行的 ASP.NET Core 服务器 https://192.168.188.31:44302使用 Web API 端点。
我可以使用 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开发新手,发现服务器端ASP.NET Core项目需要开启CORS,所以我扩展了 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 引起的.
要解决此问题,请停用 HttpsRedirection通过删除行 app.UseHttpsRedirection();在函数中 Configure或在函数 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();
});
});

关于c# - Blazor 无法连接到 ASP.NET Core WebApi (CORS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62863417/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com