【发布时间】:2020-03-01 05:04:39
【问题描述】:
我尝试使用 ajax 从我的客户端连接到 API 服务器,但在响应中出现错误: 从源“http://localhost:5003”访问 XMLHttpRequest 在“https://localhost:44381/api/webinars”已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有“访问控制允许源” ' 请求的资源上存在标头。 我试图在 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 中的控制器:
[EnableCors("AllowMyOrigin")]
[Route("api/[controller]")]
[ApiController]
public class WebinarsController : ControllerBase
{
// POST: api/Webinars
[HttpPost]
public async Task <ActionResult> PostAsync([FromBody] Item newItem)
{
//code
}
}
感谢您的回答。
【问题讨论】:
-
你应该删除你的url后面的路径后缀:
http://localhost:5003/->http://localhost:5003
标签: c# ajax api model-view-controller cross-domain-policy