[英]Enabling CORS in asp.net core
我在 .net 核心中創建了一個簡單的 api 並嘗試從反應應用程序訪問它,我收到 CORS 錯誤。 我按照 CORS 啟用了 cors 並啟用CORS with default policy and middleware
部分
https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1
我的反應應用程序中仍然出現 cors 錯誤。 不完全確定我在哪里弄錯了。
.net核心api
namespace React_NalONE_API
{
public class Startup
{
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
// options.AddPolicy(name: MyAllowSpecificOrigins,
// builder =>
// {
// builder.WithOrigins("http://localhost/*",
// "https://localhost/*");
// });
options.AddDefaultPolicy(
builder =>
{
builder.WithOrigins("http://localhost/*",
"https://localhost/*");
});
});
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers().RequireCors(MyAllowSpecificOrigins);
});
}
}
}
反應應用
componentDidMount () {
console.log("The component is now mounted")
this.setState({loading : true})
fetch('https://localhost:44391/agency')
.then(data => data.json())
.then(data => this.setState({data, loading : false}))
}
錯誤
Access to fetch at 'https://localhost:44391/agency' from origin 'http://localhost:3000' has been blocked by CORS policy: 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.
非常感謝您的幫助謝謝 R
從文檔中,您可以知道:
注意:指定的 URL 不得包含尾部斜杠 (/)。 如果 URL 以 / 結束,則比較返回 false 並且不返回 header。
根據您的要求,您似乎希望通過任何方案( http
或https
)允許來自所有來源的 CORS 請求,我建議您可以使用AllowAnyOrigin
services.AddCors(options =>
{
options.AddDefaultPolicy(
builder =>
{
builder.AllowAnyOrigin();
});
});
參考:
另一種方法是更改如下:
services.AddCors(options =>
{
options.AddDefaultPolicy(
builder =>
{
builder.WithOrigins("https://localhost:44391",
"http://localhost:44391");
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.