【发布时间】:2019-06-30 04:44:06
【问题描述】:
我有一个使用默认 WebApi 模板创建的控制器。它创建了一个这样的 post 方法:
// 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;
}
}
【问题讨论】:
-
你添加了 'config.EnableCors();'在 WebApiConfig 中?见docs.microsoft.com/en-us/aspnet/web-api/overview/security/…
-
是的,我做到了。事实上,它适用于所有其他方法,这是唯一会引发 cors 错误的方法。我用 WebApiConfig 中的代码更新了这个问题。谢谢
-
您在该新方法上添加特定 CORS 属性的任何特殊原因,即使您已经在全局范围内定义了它?如果您摆脱该属性并仅依赖全局设置,它会起作用吗?
-
@ADyson 我添加了它,因为没有它它就无法工作......而且它现在也无法使用它。没有特别的原因,只是一个实验:) 谢谢
-
@CarlosAdrian 你看到这个问题了吗stackoverflow.com/questions/18619656/enable-cors-in-web-api-2?您是否已经尝试过不同的解决方案?
标签: c# asp.net-web-api cors