【发布时间】:2021-11-14 22:53:58
【问题描述】:
当我通过 React JS 进行 axios 发布时,我在 ASP.Net Core 端收到以下 CORS 错误。
加载资源失败:Origin http://localhost:3000 is not allowed 通过访问控制允许来源。 https://localhost:5001/api/vendorregistration
我安装了以下作为我的 Nuget 包,并没有在下面应用任何其他表单,但它不起作用。
- Microsoft.AspNet.Cors。 5.2.7版本
- Microsoft.AspNetCore.Cors 2.1.1 版本
How to enable Cors for every type of request in asp.net core 3.1
Startup.cs
public class Startup
{
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.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddCors(o => o.AddPolicy("ReactPolicy", builder =>
{
builder.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin();
// .AllowCredentials();
}));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseHttpsRedirection();
app.UseCors("ReactPolicy");
app.UseMvc();
}
}
VendorRegistrationController.cs
namespace Bait.Controllers
{
[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
[EnableCors("ReactPolicy")]
ReactJS 端 RegistrationForm.tsx
const handleFormSubmit = async (values: any): Promise<any> => {
const response = await axios.post<User>('https://localhost:5001/api/vendorregistration', { data: values })
console.log(response);
};
【问题讨论】:
-
您的 cors 策略配置是正确的,我还将您的代码复制到我新创建的 asp.net core2.1 项目中,它确实有效,所以恐怕您需要重建或重新打开您的Visual Studio,然后重新启动您的应用程序并重试,我认为它更有可能不会生效。
-
@TinyWang 我卸载了项目并重新安装并添加了相同的文件。但是,当我在 ReactJS 端触发项目时,我仍然得到同样的错误。我想知道它是 HomeController.cs 还是我忘记的其他东西?
-
非常感谢先生,祝您编码愉快:)
标签: c# asp.net reactjs asp.net-core cors