拒绝没有预期结构的HTTP请求

时间:2019-11-14 21:40:35

标签: asp.net-core asp.net-core-webapi

有没有办法拒绝不遵循代码中定义的特定结构的HTTP请求?

例如,我有一个名为class的请求,我想拒绝任何正文与请求格式不同的HTTP POST请求。

    public class Request
    {
        public string Something { get; set; }
        public object Data { get; set; }
    }

1 个答案:

答案 0 :(得分:0)

只需根据需要标记一些属性,然后让模型绑定完成其余工作:

使用System.ComponentModel.DataAnnotations;

namespace MyApi.Models
{
    public class Product
    {
        public int Id { get; set; }
        [Required]
        public string Name { get; set; }
        public decimal Price { get; set; }
        [Range(0, 999)]
        public double Weight { get; set; }
    }
}

,您的webapi将如下所示:

using MyApi.Models;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace MyApi.Controllers
{
    public class ProductsController : ApiController
    {
        public HttpResponseMessage Post(Product product)
        {
            if (ModelState.IsValid)
            {
                // Do something with the product (not shown).

                return new HttpResponseMessage(HttpStatusCode.OK);
            }
            else
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
        }
    }
}

https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api

编辑

这是一些想法,甚至不确定是否可以编译,但是会带您正确的方向

[HttpPost]
[Route("api/Products")]
public HttpResponseMessage Post()
{
    using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
    {  
        var content = await reader.ReadToEndAsync();
        var model = JsonConvert.DeserializeObject<Product>(content);
        if (model == null)
        {
             return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "could not read content from body"));
        }

        foreach (PropertyInfo prop in model.GetType().GetProperties())
        {
            if (prop.GetValue(model, null) == null)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, $"missing value for property {prop.Name}");
            }
        }

        return new HttpResponseMessage(HttpStatusCode.OK);
    }
}