雖然在將 ReactJS 與 ASP.Net-Core 結合使用時,CORS 是一個大問題,但我想出了如何啟用 CORS,因此在訪問我的 UI(http://localhost:3000)時,它使用 SignalR/REST-Calls 來對抗 API(http://localhost:51761)。
這里Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(option =>
{
option.AddPolicy("myCors",
builder =>
{
builder.AllowAnyHeader().AllowAnyMethod().SetIsOriginAllowed(origin =>
{
if (origin.StartsWith("http://localhost")) return true;
if (origin.StartsWith("http://vdedarh02331")) return true;
if (origin.StartsWith("http://10.65.1.23")) return true;
return false;
});
});
});
services.AddControllers();
services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo {Title = "SimpleAPI", Version = "v1"}); });
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "SimpleAPI v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("myCors");
app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
在我的 React 應用程式中,我正在執行以下 API 呼叫:
axios
.post("http://localhost:51761/Simple/Login")
.then((response) => console.log(response))
.catch((error) => {
console.error(error);
console.log("Trying to use IP");
axios
.post("10.65.1.23:51761/Simple/Login")
.then((resp) => console.log(resp))
.catch((err) => console.error(err));
});
通過帶有 URL 的瀏覽器打開 UIhttp://10.65.1.23:3000作業正常。對 API 發出請求會導致以下錯誤。

localhost:51761呼叫不起作用是有道理的,因為瀏覽器正在嘗試呼叫瀏覽器機器上的 API。
在除錯內部函式上的服務器代碼時,SetIsOriginAllowed我認識到在我的開發機器()上使用 UI 時,每次我發出請求時總是會評估原點,localhost但在使用不同的機器時永遠不會。
我是否誤解了 CORS 或設定錯誤?謝謝你的幫助!
uj5u.com熱心網友回復:
在配置時,您需要在 URL 中提及埠號。
在Startup.cs
builder =>
{
builder.WithOrigins("http://localhost:51761")
.AllowAnyHeader()
.AllowAnyMethod();
});
此外,在控制器級別指定
[EnableCors("MyPolicy")]
public class SimpleController : Controller
uj5u.com熱心網友回復:
我自己解決了這個問題。
所以實際上你需要做的是在你的 react 專案中將代理設定package.json為 API 的 URL。此外,您需要使您的 http-request 是動態的,并將請求的內容型別設定為 non-text/html
所以改變客戶端代碼
axios
.post("http://localhost:51761/Simple/Login")
.then((response) => console.log(response))
.catch((error) => {
console.error(error);
console.log("Trying to use IP");
axios
.post("10.65.1.23:51761/Simple/Login")
.then((resp) => console.log(resp))
.catch((err) => console.error(err));
});
到
axios
.post(
"/Simple/Login",
{},
{ headers: { "Content-Type": "application/json" } }
)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.error(error);
console.log("Trying to use IP");
axios
.post(
"/Simple/Login",
{},
{ headers: { "Content-Type": "application/json" } }
)
.then((resp) => {
console.log(resp);
})
.catch((err) => console.error(err));
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/475990.html
標籤:C# 反应 asp.net 核心 http-status-code-400 连接被拒绝
