r3plica
r3plica

Reputation: 13367

Posting to Web Api parameters are null

I have a jquery method which looks like this:

$.post("/api/amazon/signature", { "policy": policy }, function (data) {
    console.log(data);
});

the api method looks like this~:

// POST api/amazon/signature
[HttpPost]
[Route("api/amazon/signature")]
public IHttpActionResult GetSignature([FromBody]string policy)
{
    var bKey = Encoding.ASCII.GetBytes(ConfigurationManager.AppSettings["AWSSecretKey"]);
    var hmacSha1 = new HMACSHA1(bKey);

    var bPolicy = Encoding.ASCII.GetBytes(policy);
    var hash = hmacSha1.ComputeHash(bPolicy);
    var encoded = Convert.ToBase64String(hash);

    return Ok(encoded);
}

but when I run this code policy is always null! If I change my method to this:

public class Signature
{
    public string Policy { get; set; }
}

// POST api/amazon/signature
[HttpPost]
[Route("api/amazon/signature")]
public IHttpActionResult GetSignature([FromBody]Signature model)
{
    var bKey = Encoding.ASCII.GetBytes(ConfigurationManager.AppSettings["AWSSecretKey"]);
    var hmacSha1 = new HMACSHA1(bKey);

    var bPolicy = Encoding.ASCII.GetBytes(model.Policy);
    var hash = hmacSha1.ComputeHash(bPolicy);
    var encoded = Convert.ToBase64String(hash);

    return Ok(encoded);
}

and modify my jquery to this:

$.post("/api/amazon/signature", { "Policy": policy }, function (data) {
    console.log(data);
});

it works fine....

Can someone tell me why?

Upvotes: 0

Views: 145

Answers (1)

ASP.NET Web API binds the request body in its entirety to one parameter (one parameter only and not more). By default, body is bound to a complex type. So, when you change the parameter type to Policy which is a complex type, you don't need to actually specify FromBody. Also binding works correctly now because you are sending JSON Object which looks something like this { "policy": policy }. Web API has no trouble in binding JSON object to your complex type.

When it comes to a simple type, string in your case, you must specify FromBody, since by default Web API binds from URI path and query string. In that case however, you cannot send a JSON Object. Web API is going to bind the entire body to that parameter, which is string. So, the request body must be just a string like this - "ABC123" and not a JSON object. If you send just "ABC123" (including the quotes) in the request body, your string parameter will be populated with ABC123.

Upvotes: 1

Related Questions