ASP.Net Web API custom model binding with x-www-form-urlencoded posted data - nothing seems to work

前端 未结 2 1067
独厮守ぢ
独厮守ぢ 2021-02-03 10:18

I am having a lot of trouble getting custom model binding to work when posting x-www-form-urlencoded data. I\'ve tried every way I can think of and nothing seems to

2条回答
  •  逝去的感伤
    2021-02-03 10:37

    ModelBinder seem relatively better to use than MediaTypeFormatter. You do not need to register it globally.

    I found another alternative to use model binder to bind complex object types in Web API. In model binder, I am reading request body as string and then using JSON.NET to deserialize it to required object type. It can be used to map array of complex object types as well.

    I added a model binder as follows:

    public class PollRequestModelBinder : IModelBinder
    {
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            var body = actionContext.Request.Content.ReadAsStringAsync().Result;
            var pollRequest = JsonConvert.DeserializeObject(body);
            bindingContext.Model = pollRequest;
            return true;
        }
    }
    

    And then I am using it in Web API controller as follows:

        public async Task Post(Guid instanceId, [ModelBinder(typeof(PollRequestModelBinder))]PollRequest request)
        {
           // api implementation  
        }
    

提交回复
热议问题