验证HttpRequestMessage正文

时间:2017-12-01 19:10:30

标签: c# json asp.net-web-api controller

我有一个web api,我想验证进来的请求。

目前我的web api控制器中有这个:

public HttpResponseMessage GetSomething([FromBody]SomeObject request)
{
    var test= request.Number;
    //omit
}

public class SomeObject
{
    [JsonProperty]
    public double Number {get;set;}
}

目前,如果我发送请求并将Number设置为字符串或非double,则当请求到达服务器时,Number仅设置为零。我应该如何验证请求,因为我没有'当它进来时希望它为零?

2 个答案:

答案 0 :(得分:2)

要收到错误并返回给用户,您可以检查控制器API的ModelState属性。

public IHttpActionResult Post([FromBody]SomeObject value)
{
    if(this.ModelState.IsValid)
    {
        // If you enter here all data are set correctly
        return Ok();
    }
    else
    {
        // here you use BadRequest method and pass the ModelState property.
        return this.BadRequest(this.ModelState);
    }
}

无所事事,可以更改Number财产。我做的唯一修改是使用IHttpActionResult更改操作的返回类型。

如果Number的数据设置不正确,您将在客户端网站上进行类似的操作:

{
    "Message": "The request is invalid.",
    "ModelState": {
        "value.number": [
            "Error converting value \"dfsdf\" to type 'System.Double'. Path 'number', line 2, position 19."
        ]
    }
}

答案 1 :(得分:0)

通过使用此过滤器注释it方法,可以在所有控制器中重用此方法。

[Valid] //here  we apply the filter and request made to this model is validated by validation rules on the model
[HttpPost]
 public HttpResponseMessage someMethod(SomeValidationModel someValidationModel)
 {
    //some logic
 }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace mynamespace.filters
{
    public class ValidAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {

            if (!actionContext.ModelState.IsValid)
            {
                actionContext.Response = actionContext.Request.CreateErrorResponse(
                HttpStatusCode.BadRequest, actionContext.ModelState);
            }
        }
    }
}