1

I am using custom model binder in web api, but my model value is null.

It is unable to get the value from ValueProvider.

Please look at my code below.

bindingContext.ValueProvider.GetValue("Report") is null

Here is my code.

public class TestReportDto
    {
        public ReportFormatType ExportFormat { get; set; }
        public string Report { get; set; }
        public Dictionary<string, object> ParameterValues { get; set; }
    }

    public enum ReportFormatType
    {
        PDF,
        XLS
    }

My Model Binder class.

public class TestModelBinder : IModelBinder
    {
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            var testReportDto = new TestReportDto();
            bool isSuccess = true;

            if (bindingContext.ValueProvider.GetValue("Report") != null)
            {
                testReportDto.Report = Convert.ToString(bindingContext.ValueProvider.GetValue("Report").RawValue);
            }
            else
            {
                isSuccess = false;
                bindingContext.ModelState.AddModelError("request.Report", "Report");
            }

            bindingContext.Model = testReportDto;
            return isSuccess;
        }
    }

API Code:

public async Task<string> Post([ModelBinder(typeof(TestModelBinder))]TestReportDto request)
        {

            return "Hello";
        }
Programmer
  • 398
  • 1
  • 9
  • 33
  • 1
    How you send data to your POST action? Could you provide code example? – Alexander I. Aug 30 '18 at 14:30
  • @AlexanderI. : I'm sending it from postman. see my request [here](https://i.stack.imgur.com/AJAvO.png) . Also I have set `Content-Type` is to `application/json` – Programmer Aug 31 '18 at 06:09

1 Answers1

0

You can get the value from the Request object of the HttpActionContext object inside your custom model binder. The example I used is below.

var bodyContent = actionContext.Request.Content.ReadAsStringAsync().Result;

Please note that this is quick and dirty solution for the problem you're facing. If you would play by the rules then you should create provider class for handling that kind of data (body content), and then a factory class to engage the whole process correctly. Just like it's described here.

josip.k
  • 171
  • 2
  • 9
  • for synchronous calls do not use `.Result` use instead `GetResult()` see [this](https://stackoverflow.com/questions/17284517/is-task-result-the-same-as-getawaiter-getresult/38530225#38530225) – Diego Osornio Jan 31 '19 at 23:36
  • also for the APIs consider using instead the `async` calls like `var bodyContent = await actionContext.Request.Content.ReadAsStringAsync();` – Diego Osornio Jan 31 '19 at 23:37