10

I upgraded from MVC4 beta to RC and the latest autofac. The following action was binding properly, but now both parameters are null. I see they changed things about the Formatters and such but I am not sure what caused my problem

[HttpPost]    
RedirectModel MyAction(string value1, string value1)

REQUEST

Method: POST
Accept: application/json
URL: api/controller/myaction
BODY: {"value1":"1000", "value2":"foo"}

2 Answers 2

20

When you want to avoid using a DTO object, try this:

[HttpPost]    
RedirectModel MyAction(dynamic value1, dynamic value2) {
    string sValue1 = value1;
    string sValue2 = value2;
1
  • 2
    You are a hero. This is the only viable solution in my very specific case. I can't believe I didn't think of it before. I wish I could give you additional upvotes. Cheers. Oct 24, 2012 at 16:17
11

Not really sure why the change from Beta, but I was able to make it work by changing the action signature to:

[HttpPost]    
RedirectModel MyAction(MyActionDTO dto)

and defining MyActionDTO as

 public class MyActionDTO 
 {
        public string value1 { get; set; }
        public string value2 { get; set; }
 }

It was throwing an exception about not being able to bind to multiple body parameters using the two string paramaters. I guess using the DTO object more closely represents what you're sending in the AJAX call (a JSON object).

6
  • 2
    Adding [FromBody] to the parameters did not having any effect, the parameters were still null.
    – Thad
    Jun 11, 2012 at 13:05
  • That does work, but I was hoping not to have to change it. We do have a few calls that have a single string in the body. I not sure why a single primitive types is required to be on the query string.
    – Thad
    Jun 11, 2012 at 20:48
  • According to this:blogs.msdn.com/b/jmstall/archive/2012/04/16/…, you can pass one and only one item in the body. So, if you want to pass a string value, you can do that, just pass the value without wrapping it as a JSON string.
    – Jim Harte
    Jun 12, 2012 at 16:16
  • asp.net site updated today with more info: asp.net/web-api/overview/working-with-http/… Note you must prefix the value with an equal sign (=) when posting a simple value in the body
    – Jim Harte
    Jun 16, 2012 at 2:04
  • Thank you very much , binding parameters to C# class works fine for me .I want to ask why I can send parameters only to HttpPost WebApi actions , can I send parameters to HttpGet Web Api action ?
    – Omar Isaid
    Jan 22, 2018 at 17:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.