Can I get access to the data that the .net web api model binding was not able to handle?

拟墨画扇 提交于 2019-12-11 08:17:57

问题


I have a MVC 4 web api application that receives json objects and uses the standard model binding facility to bind them to my poco objects for easy use in my controller methods.

This all works great, when the json structures I am receiving map directly to my poco. for example I have a controller method

 public HttpResponseMessage Post(DeviceConfigurationDto deviceConfiguration)

and DeviceConfigurationDto is

public class DeviceConfigurationDto
    {
        public long Timestamp { get; set; }
        public string DeviceType { get; set; }
        public string AssetName { get; set; }
    }
}

and I post the following JSON

 {
        "Timestamp": 234234234,
        "DeviceType": "A555tom",
        "AssetName": "HV103"
    }

The built in model binding facility does a pretty good job of working with variations, like extra fields or fields missing and so forth. But if you push it to far. for example by posting the following json

    [
    {
        "Fields4": "asda",
        "Timestamp": 234234234,
        "DeviceType": "A555tom",
        "AssetName": "HV103"
    },
    {
        "Timestamp": 234234234,
        "DeviceType": "A555tom",
        "DedviceType": "A555tom",
        "AssetName": "HV103"
    }
]

It eventually falls over and I end up with the parameter into my method being null.

Is there a way for the model binding to work when the data is as expected, but then also provide me with the ability to get to the data that was a problem for the model binder, so that I can log the request that I am receiving that are not matching what I expected?

Thanks


回答1:


One way to do this is to use custom ActionFilter. Since model binding happens before an action filter is executed, you can get your action argument(s) in your a custom action filter.

For example:

public class LogFailToModelBindArgActionFilterAttribute : System.Web.Http.Filters.ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext context)
    {
        var deviceConfigurationArg = context.ActionArguments["deviceConfiguration"];
        if (deviceConfigurationArg == null) // fail to model bind data to argument ...
        {
            var jsonContent = context.Request.Content.ReadAsStringAsync().Result; // calling .Result here for sake of simplicity...
            Log(jsonContent);
        }
    }
}

Action:

    [LogFailToModelBindArgActionFilter]
    public HttpResponseMessage Post(DeviceConfigurationDto deviceConfiguration)
    {...}


来源:https://stackoverflow.com/questions/12967254/can-i-get-access-to-the-data-that-the-net-web-api-model-binding-was-not-able-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!