0

我正在使用 ASP.NET 的ApiController类来创建 Web API。我发现如果我传递无效的 JSON,而不是调用者得到 500,输入参数为空。就像,如果我通过

{ "InputProperty:" "Some Value" }

对于这种方法,这显然是无效的:

[HttpPost]
public Dto.OperationOutput Operation(Dto.OperationInput p_input)
{
    return this.BusinessLogic.Operation(p_input);
}

我明白了p_inputnull我宁愿发回一些东西告诉用户他们没有发布有效的 JSON。

在我的WebApiConfig.cs,我有:

config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
config.Formatters.XmlFormatter.UseXmlSerializer = true;

有任何想法吗?我确实看到了这个例子,但我相信那是 ASP.NET MVC,而不是 ApiController。

4

1 回答 1

1

编辑:我已经使类的输出更加具体并更改了状态代码。我开始进行这些更改,后来看到@CodeCaster 的第二条评论。

public class ModelStateValidFilterAttribute : System.Web.Http.Filters.ActionFilterAttribute
{
    /// <summary>
    /// Before the action method is invoked, check to see if the model is
    /// valid.
    /// </summary>
    public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext p_context)
    {
        if (!p_context.ModelState.IsValid)
        {
            List<ErrorPart> errorParts = new List<ErrorPart>();

            foreach (var modelState in p_context.ModelState)
            {
                foreach (var error in modelState.Value.Errors)
                {
                    String message = "The request is not valid; perhaps it is not well-formed.";

                    if (error.Exception != null)
                    {
                        message = error.Exception.Message;
                    }
                    else if (!String.IsNullOrWhiteSpace(error.ErrorMessage))
                    {
                        message = error.ErrorMessage;
                    }

                    errorParts.Add(
                        new ErrorPart
                        {
                            ErrorMessage = message
                          , Property = modelState.Key
                        }
                    );
                }
            }

            throw new HttpResponseException(
                p_context.Request.CreateResponse<Object>(
                    HttpStatusCode.BadRequest
                  , new { Errors = errorParts }
                )
            );
        }
        else
        {
            base.OnActionExecuting(p_context);
        }
    }
}

原始答案: 感谢@CodeCaster 的指针,我正在使用以下内容,它似乎有效:

/// <summary>
/// Throws an <c>HttpResponseException</c> if the model state is not valid;
/// with no validation attributes in the model, this will occur when the
/// input is not well-formed.
/// </summary>
public class ModelStateValidFilterAttribute : System.Web.Http.Filters.ActionFilterAttribute
{
    /// <summary>
    /// Before the action method is invoked, check to see if the model is
    /// valid.
    /// </summary>
    public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext p_context)
    {
        if (!p_context.ModelState.IsValid)
        {
            throw new HttpResponseException(
                new HttpResponseMessage
                {
                    Content = new StringContent("The posted data is not valid; perhaps it is not well-formed.")
                  , ReasonPhrase = "Exception"
                  , StatusCode = HttpStatusCode.InternalServerError
                }
            );
        }
        else
        {
            base.OnActionExecuting(p_context);
        }
    }
}
于 2013-11-26T18:44:30.773 回答