【问题标题】:Validating HttpRequestMessage body验证 HttpRequestMessage 正文
【发布时间】:2017-12-01 19:10:29
【问题描述】:

我有一个 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 设置为字符串或非双精度,则当请求到达服务器时,Number 只是设置为零。当请求进来时我应该如何验证请求,因为我不希望它在进来时为零?

【问题讨论】:

  • 在这种情况下,您将向客户端发送 400 Bad Request http 状态响应。除非您收到请求,否则无法验证它,因此您无法阻止客户端尝试发送垃圾。
  • @Crowcoder 在服务器端,垃圾只是将 number 属性设置为零,但这会将其转换为有效请求。我无法检查数字零
  • 如果 Number 是一个可为空的 int (?) 你会得到 null 吗?
  • @Crowcoder 是的,可以,谢谢你的想法
  • @DeVonte 您无需更改属性的类型即可使其正常工作。请看下面我的回答。

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


【解决方案1】:

要获得错误并返回给用户,您可以检查控制器 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."
        ]
    }
}

【讨论】:

    【解决方案2】:

    通过使用此过滤器注释 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);
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-18
      • 2014-07-11
      • 2021-05-06
      • 1970-01-01
      相关资源
      最近更新 更多