【发布时间】:2019-01-04 16:15:21
【问题描述】:
我使用 asp.net core 2.1 构建 web API 并在我的 web 上使用 ajax 来请求 api。
首先我在 GET 方法上遇到问题,我使用 chrome plugin 来解决问题。
但我仍然无法使用 post 方法。
在网页上
POST https://localhost:5001/api/chatbot 400 (Bad Request)
Visual Studio 显示异常。
[40m[32minfo[39m[22m[49m:Microsoft.AspNetCore.Hosting.Internal.WebHost1 请求启动 HTTP/1.1 OPTIONS https://localhost:5001/api/chatbot
Microsoft.AspNetCore.Hosting.Internal.WebHost:信息:请求启动 HTTP/1.1 选项https://localhost:5001/api/chatbot
Microsoft.AspNetCore.Cors.Infrastructure.CorsService:信息:策略执行失败。 [40m[32minfo[39m[22m[49m:Microsoft.AspNetCore.Cors.Infrastructure.CorsService[5] 策略执行失败。 [40m[32minfo[39m[22m[49m:Microsoft.AspNetCore.Cors.Infrastructure.CorsService[7] CORS 策略中不允许请求方法 POST。 Microsoft.AspNetCore.Cors.Infrastructure.CorsService:信息:CORS 策略中不允许请求方法 POST。 [40m[32minfo[39m[22m[49m:Microsoft.AspNetCore.Hosting.Internal.WebHost[2] 请求在 21.587 毫秒内完成 204
我已经在 Startup.cs 中使用了 cors - ConfigureServices()
options.AddPolicy("CorsPolicy", policy =>
{
policy.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
Startup.cs - Configure()
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
string swwwRootPath = env.WebRootPath;
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseStaticFiles();
app.UseAuthentication();
//app.UseHttpsRedirection();
app.UseExceptionHandler("/Error");
//app.UseCors(builder =>
//builder.WithOrigins("file:///").AllowAnyHeader());
app.UseCors("CorsPolicy");
app.UseCors(builder => {
builder.WithOrigins("file:///").AllowAnyHeader();
});
app.UseMvc();
}
还有我的 ajax 函数
var json = {"channel":"web", "message":"", "messagetype":"text", "userid":"xxx", "nodeid":nodeid};
$.ajax({
method: 'POST',
url: "https://localhost:5001/api/chatbot",
data: json,
datatype: "json",
contentType: "application/json; charset=utf-8",
success:...
我的控制器
[ApiController]
[Route("api/[controller]")]
public class ChatbotController : Controller
{
[HttpPost]
[EnableCors("CorsPolicy")]
[Produces("application/json")]
public ActionResult<string> Post([FromBody]RequestModel request)
{...
RequestModel
public class RequestModel
{
public string channel { get; set; }
public string message { get; set; }
public string messagetype { get; set; }
public string userid { get; set; }
public string nodeid { get; set; }
}
GET 和 POST 方法都可以在我使用 Postman 时得到正确的响应。
有人知道怎么解决吗?谢谢。
【问题讨论】:
-
顺便说一句,
Access-Control-Allow-*标头必须由服务器在 response 中发送给 OPTIONS 请求,而不是 request中的客户端> 看来你在这里尝试...
标签: c# .net ajax asp.net-core cors