1

How can I set up an ApiController so that I can bind the method parameters to both a parameterized route and the request parameteres (in this case a POST, but PUTs as well)?

Something along the lines of

public class MessageController : ApiController
{
    public class Message
    {
       public string Content { get; set; }
       public int Priority { get; set; }
    }

    [Route( "Data/Message/{apiKey}/{userId}" )] 
    [HttpPost]
    public Message Post( Guid apiKey, string userId, Message msg)
    {
        // ...
    }
}

So that this would work

$.post('/Data/Message/<some key>/<some id>', { 
    Content: 'Did you receive my payment?', 
    Priority: 0 
 });

I tried the method from Accessing route and POST params in Web Api 2 Controller Method of using a class and having the parameters bound to its properties, but this does not work. The parameter is simply always null.

1 Answer 1

4

Use the [FromBody] attribute

[Route("Data/Message/{apiKey}/{userId})]
[HttpPost]
public Message Post(Guid apiKey, string userId, [FromBody] Message msg)
{
    ...
}

Then your Message class property names should match your javascript data object.

var data = {
    Content: 'Did you receive my payment?',
    Priority: 0
};

$.post('/Data/Message/<some key>/<some id>', data);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.