I am porting my web application from MVC5 to MVC6. This function used to work fine in MVC5 but not in MVC6.
I am posting data, via AngularJS, to this WebAPI method but the search parameter is always null. Ive tried decorating it with [FromBody] and [FromHeader] but neither seem to work. The controller gets hit, the value is just null, what is wrong?
[HttpPost("AdvancedSearch")]
public List<MatchResult> AdvancedSearch(string searchParameter)
{
var searchResults = service.GetResults(searchParameter);
return searchResults;
}
My AngularJS call looks like this
myAPI.advancedSearch = function (searchParameter) {
var url = '/api/advancedsearch/';
// Request data
return $http({
method: 'POST',
data: { searchParameter: searchParameter },
url: url
});
}
I verified that the data is sent, in Chrome webtools the "Request Payload" is correct
{searchParameter: "n1"}
I found a way to do this without using a model or querystring. This answer explains it but essentially you can use
[HttpPost]
public System.Net.Http.HttpResponseMessage Post([FromBody]dynamic value)
{
//...
}
value will then contains all your post data.
Edit
For further reading please see this post, including a table of all the binding situations and when it will and won't work!
If you think an object is overkilling, you can always use querystrings. I know, looks "old", but it's still working I guess.
myAPI.advancedSearch = function (searchParameter) {
var url = '/api/advancedsearch?searchParameter=' + searchParameter ;
// Request data
return $http({
method: 'POST',
data: { },
url: url
});
}
[HttpPost("AdvancedSearch")]
public List<MatchResult> AdvancedSearch([FromQuery]string searchParameter)
{
var searchResults = service.GetResults(searchParameter);
return searchResults;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With