0

I was looking at https://stackoverflow.com/a/15873977 but it didn't work for me.

If my Post method has a parameter named Message (an object of my own class), and I do not apply the [FromBody] attribute to it, is it possible to pass the parameter Message, json serialized and urlEncoded, on the query string instead of in the Post body?

I tried passing ?Message=%7B+%22Sender%22%3A...+%7D (which if decoded would be Message={ "Sender":... }) but the Message parameter is still received as null in the method.

Should the query string key be Message, the name of the parameter, or the class name of the parameter or something else?

Community
  • 1
  • 1
Old Geezer
  • 14,854
  • 31
  • 111
  • 198

1 Answers1

2

If you have a model Foo:

public class Foo
{
    public string Bar { get; set; }
    public int Baz { get; set; }
}

And you want to bind this from the query string, then you must address the individual properties:

?Bar=qux&Baz=42

And annotate that the model must be bound from the query string:

public void Bar([FromUri]Foo foo)
{
}

If you really want to send JSON into your action method and not a model, simply bind to a string instead of a model. You can then do whatever you want with the JSON string inside your action method.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • Does that mean that I must decide between `[FromUri]` or `[FromBody]` and cannot offer the flexibility of either to the caller? – Old Geezer Jun 03 '16 at 10:14
  • 1
    Why would you want to offer such flexibility? Note that you will pay in maintainability. Anyway [yeah, you can](http://stackoverflow.com/questions/17645877/webapi-bind-from-both-uri-and-body). – CodeCaster Jun 03 '16 at 10:16