【发布时间】:2018-07-20 13:47:35
【问题描述】:
我已经被这个问题难住了好几天了。我是 CORS 的初学者,所以在导航过程中非常混乱。
出了什么问题: 我创建了一个 asp.net web api,它可以成功地将 POST 请求发送到我的 SQL 数据库。我已经使用 POSTMAN 成功发送数据。启用 CORS 后,我将无法再发送数据。我收到 400 错误请求。
我的代码的一些参考:
处理 POST 请求的我的控制器:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using ClientsDataAccess;
namespace MS_Clients_Post.Controllers
{
public class ClientsController : ApiController
{
public HttpResponseMessage Post([FromBody] Client client)
{
try
{
using (NewlandiaEntities entities = new NewlandiaEntities())
{
entities.Clients.Add(client);
entities.SaveChanges();
var message = Request.CreateResponse(HttpStatusCode.Created, client);
message.Headers.Location = new Uri(Request.RequestUri +
client.Id.ToString());
return message;
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
}
}
我的 webAPIconfig.cs 文件(我在其中启用了 CORS):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Cors;
namespace MS_Clients_Post
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
//enabling cors. The "*","*","*" attributes allow all to access. This should be more limited acccess in the future.
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
//end of cors code.
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
我在 Fiddler 中看到的内容: OPTIONS Response 200 (Only returned with Angular APP, not POSTMAN
还有POST Response 400 BAD REQUEST (With POSTMAN or Angular APP
TLDR; 使用 ASP.net Web API 的 POST 请求在启用 CORS 之前有效。为什么之后就不行了?
非常感谢任何帮助!
【问题讨论】:
标签: c# asp.net-mvc post cors http-status-code-400