在我的webApi中,我将所有方法都放在一个控制器中,并将路由附加到每个方法上,如下所示:
[HttpPost]
[Route("api/Users/Notary/Seal/Generate")]
public IHttpActionResult GenerateNotarySeal([FromBody]GenerateSealContract SealInfo)
{
return Ok(new RestResponse<byte[]>(buffer));
}
当我用招摇过头测试我的webApi时,它会执行预检OPTIONS请求,以确保正确设置“ Access-Control-Allow-Headers”。要对此做出回应,我要做类似的事情:
[HttpOptions]
[Route("api/Users/Notary/Seal/Generate")]
public IHttpActionResult OptionsHandler([FromBody]GenerateSealContract SealInfo)
{
///.... I set my custom headers in ActionFilterAttribute
return Ok();
}
但是我不想为每个方法重复此代码。有什么方法可以仅对OPTIONS请求执行通配符吗?像这样:
[HttpOptions]
[Route("api/*")]
public IHttpActionResult OptionsHandler()
{
///.... I set my custom headers in ActionFilterAttribute
return Ok();
}
答案 0 :(得分:1)
首先,我认为您应该检查发现的here
的常规属性路由约束第二步可以完成,但是您必须实现自己的Custom Route Constraint,但它可能不会是通配符(*)。
来自上面的Microsoft文档链接:
您可以通过实现IHttpRouteConstraint接口来创建自定义路由约束。例如,以下约束将参数限制为非零整数值。
public class NonZeroConstraint : IHttpRouteConstraint
{
public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName,
IDictionary<string, object> values, HttpRouteDirection routeDirection)
{
object value;
if (values.TryGetValue(parameterName, out value) && value != null)
{
long longValue;
if (value is long)
{
longValue = (long)value;
return longValue != 0;
}
string valueString = Convert.ToString(value, CultureInfo.InvariantCulture);
if (Int64.TryParse(valueString, NumberStyles.Integer,
CultureInfo.InvariantCulture, out longValue))
{
return longValue != 0;
}
}
return false;
}
}
以下代码显示了如何注册约束:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
var constraintResolver = new DefaultInlineConstraintResolver();
constraintResolver.ConstraintMap.Add("nonzero", typeof(NonZeroConstraint));
config.MapHttpAttributeRoutes(constraintResolver);
}
}
现在您可以在路线中应用约束:
[Route("{id:nonzero}")]
public HttpResponseMessage GetNonZero(int id) { ... }
您还可以实现自定义ActionFilter,在其中您可以访问HttpRequst,包括请求标头
public class CustomActionFilter: ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
// Before Execution
}
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
//On Execution
}
}
然后您可以应用CustomActionFilter