我尝试使用 ajax 从我的侧客户端连接到 API 服务器,但我在响应中收到错误:
访问 XMLHttpRequest ' https://localhost:44381/api/webinars '来自原点' http://localhost:5003 ' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin” header 。
我尝试在 API 中编辑 CROS 策略,但仍然出现相同的错误。
这是我来自 MVC 的 ajax 代码:
$.ajax({
url: "https://localhost:44381/api/webinars",
type: 'POST',
headers: {
contentType: "application/json",
},
body: JSON.stringify(body),
success: function (data) {
console.log(data);
},
failure: function (err) {
console.log(err);
}
});
从 API 启动:
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("AllowMyOrigin",
builder => builder.WithOrigins(
"http://localhost:5003/",
"http://apirequest.io")
.WithMethods("POST","GET","PUT")
.WithHeaders("*")
);
});
//code
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//code
app.UseCors("AllowMyOrigin");
app.UseHttpsRedirection();
app.UseMvc();
}
}
API 中的 Controller :
[EnableCors("AllowMyOrigin")]
[Route("api/[controller]")]
[ApiController]
public class WebinarsController : ControllerBase
{
// POST: api/Webinars
[HttpPost]
public async Task <ActionResult> PostAsync([FromBody] Item newItem)
{
//code
}
}
谢谢你的回答。
最佳答案
你应该替换 app.UseMvc();
和
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
关于c# - ASP.NET CORE 中的 CORS 策略阻止了对 XMLHttpRequest 的访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58700916/