Web Web API中的严格映射(过量发布) [英] Strict mapping in web Web API (Over-Posting)

查看:173
本文介绍了Web Web API中的严格映射(过量发布)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚意识到查询发送的JSON与我的API之间的映射并不严格.

I just realized that the mapping between the JSON send from a query and my API is not strict.

我给你更多的解释:

这是我的C#POCO

Here is my C# POCO

public partial class AddressDto
{
    public string AddrId { get; set; }
    public string Addr1 { get; set; }
    public string Addr2 { get; set; }
    public string PostalCode { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
}

和REST JSON查询

And the REST JSON query

PUT http://Localhost:55328/api/ClientAddr/ADD-2059-S002 HTTP/1.1
content-type: application/json

{
    "AddrID": "ADD-2059-S002",
    "addr1": "B-1/327",
    "addr2": "1ST FLOOR",
    "city": "Paris",
    "Zip_Code": "78956",
    "country": "France",
}

Web客户端发送带有Zip_Code的PUT来代替PostalCode.邮递区号不是必填项.但是我的DTO中不存在Zip_Code.

The web client send a PUT with Zip_Code in place of PostalCode. PostalCode is not madatory/required. But Zip_Code does not exist in my DTO.

因此在我的C#代码中,测试模型状态将无济于事.

So in my C# code testing the model state won't help.

public HttpResponseMessage Put(string id, AddressDto address)
{
     if (!ModelState.IsValid)
            return BadRequest(ModelState); // This wont help
}

当客户端使用JSON中的DTO(模型)中不存在的内容时,如何引发异常?

How can I raise exception when the client is using something in the JSON that is not existing in my DTO (model) ?

推荐答案

如果您需要标识额外的列并将其作为错误处理,则必须扩展IModelBinder接口,并告诉json反序列化器将多余的列视为错误并添加ModelState错误.通过这种方式,您可以在控制器中签入ModelState.IsValid.检出下面的代码

if you need to identify extra columns and handle that as an error you have to extend IModelBinder interface and tell json deserializer to treat extra column as an error and add that error to ModelState. By that way you can check in controller for ModelState.IsValid. Checkout the below Code

CustomModelBinder

CustomModelBinder

public class CustomModelBinder : IModelBinder
{
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        JsonSerializerSettings settings = new JsonSerializerSettings();
        settings.MissingMemberHandling = MissingMemberHandling.Error;
        ObjToPass obj = new ObjToPass();
        ;
        try
        {
            ObjToPass s =
                JsonConvert.DeserializeObject<ObjToPass>(actionContext.Request.Content.ReadAsStringAsync().Result,
                    settings);


            bindingContext.Model = obj;
        }
        catch (Exception ex)
        {
            bindingContext.ModelState.AddModelError("extraColumn", ex.Message);
        }
        return true;
    }
}

public class CustomerOrderModelBinderProvider : ModelBinderProvider
{
    public override IModelBinder GetBinder(System.Web.Http.HttpConfiguration configuration, Type modelType)
    {
        return new CustomModelBinder();
    }
}

传递给webapi的对象类

Object Class that is passed to webapi

 public class ObjToPass
{
    public int Id { get; set; }
    public string Name { get; set; }

}

控制器

 [HttpPost]
    public void PostValues([ModelBinder(typeof(CustomerOrderModelBinderProvider))] ObjToPass obj)
    {
        if(!ModelState.IsValid)
        { }
        else
        {

        }
    }

此示例也适用于HttpPut.

This sample holds good for HttpPut as well.

这篇关于Web Web API中的严格映射(过量发布)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆