我正在尝试处理OData查询选项不正确(例如空扩展)的情况。如果查询错误,我希望返回 400 状态代码而不是 500 。
http://localhost:51625/odata/persons(123)?$expand=
我已经实现了自定义 ODataEnableQueryAttribute ,该继承自 EnableQueryAttribute ,并将其用于控制器的操作。 我覆盖了 EnableQueryAttribute 中的所有方法,并在try ... catch块中调用了基本的方法
public class ODataEnableQueryAttribute : EnableQueryAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
try
{
base.OnActionExecuting(context);
}
catch (Exception ex)
{
context.Result = new OAIncorrectQueryResult(ex.Message);
}
}
public override void OnActionExecuted(ActionExecutedContext actionExecutedContext)
{
try
{
base.OnActionExecuted(actionExecutedContext);
}
catch (Exception ex)
{
actionExecutedContext.Result = new OAIncorrectQueryResult(ex.Message);
}
}
}
但是我的自定义属性中没有一种方法被调用。 我收到了ArgumentException“'select'和'expand'不能都为null或为空。从ODataQueryParameterBindingAttribute继承。 堆栈跟踪:
at Microsoft.AspNet.OData.Query.SelectExpandQueryOption..ctor(String select, String expand, ODataQueryContext context, ODataQueryOptionParser queryOptionParser)
at Microsoft.AspNet.OData.Query.ODataQueryOptions.BuildQueryOptions(IDictionary`2 queryParameters)
at Microsoft.AspNet.OData.Query.ODataQueryOptions.Initialize(ODataQueryContext context)
at Microsoft.AspNet.OData.Query.ODataQueryOptions`1..ctor(ODataQueryContext context, HttpRequest request)
at Microsoft.AspNet.OData.ODataQueryParameterBindingAttribute.ODataQueryParameterBinding.CreateODataQueryOptions[T](ODataQueryContext context, HttpRequest request)
at Microsoft.AspNet.OData.ODataQueryParameterBindingAttribute.ODataQueryParameterBinding.BindModelAsync(ModelBindingContext bindingContext)
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextExceptionFilterAsync()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ExceptionContext context)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
可能是从创建ODataQueryOptions的地方引发的异常。 (第86行-https://github.com/OData/WebApi/blob/master/src/Microsoft.AspNet.OData/ODataQueryParameterBindingAttribute.cs#L86)
因此,如何通过返回400错误而不是500错误来处理无效的查询选项