我有一个使用默认WebApi模板创建的控制器。它创建一个像这样的发布方法:
// POST: api/PedidosVenta
[HttpPost]
[ResponseType(typeof(PedidoVentaDTO))]
public async Task<IHttpActionResult> PostPedidoVenta(PedidoVentaDTO pedido)
这时,CORS在我的计算机和其他域中都可以正常工作。然后,我需要使用其他路由的第二种post方法,并以此方式创建它:
[HttpPost]
[EnableCors(origins: "*", headers: "*", methods: "POST")]
[Route("api/PedidosVenta/SePuedeServirPorAgencia")]
public async Task<RespuestaAgencia> SePuedeServirPorAgencia(PedidoVentaDTO pedido)
即使我调用此方法,它也可以在我的计算机上正常工作,但是当我尝试从其他域运行时,它将引发CORS错误(仅当我调用此方法时,所有其他方法都可以正常工作)。>
我无法解决它,所以我确定我缺少重要的东西。有人可以帮我用这种方法正确配置cors吗?
谢谢
更新:我粘贴了WebApiConfig的代码:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize;
config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
var cors = new System.Web.Http.Cors.EnableCorsAttribute(
origins: "*",
headers: "*",
methods: "*");
config.EnableCors(cors);
GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
}
}
答案 0 :(得分:0)
global.asax
中的这段代码成功了:
protected void Application_BeginRequest(object sender,EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if(HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000" );
HttpContext.Current.Response.End();
}
}
来自405 method options not allowed in asp.net web api controller?
然后,我还必须从WebApiConfig.cs中删除CORS,因为它是重复的并给出了另一个错误:The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed