传递无效JSON的API控制器接收null

时间:2013-11-26 18:03:34

标签: c# asp.net-web-api asp.net-apicontroller

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

{ "InputProperty:" "Some Value" }

这个方法明显无效:

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

我认为p_inputnull。我宁愿发回一些东西告诉用户他们没有POST有效的JSON。

在我的WebApiConfig.cs中,我有:

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

有什么想法吗?我确实看到了this example,但我相信它是ASP.NET MVC,而不是ApiController。

1 个答案:

答案 0 :(得分: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);
        }
    }
}