Reputation: 11340
I have the following method in my web api
public class AccessPanelController : ApiController
{
public HttpResponseMessage PostGrantAccess([FromUri]GrantAccessRequest grantAccessRequest)
{
var deviceId = grantAccessRequest.DeviceId;
var grantAccessResponse = new GrantAccessResponse()
{
Status = "OK"
};
var response = Request.CreateResponse<GrantAccessResponse>(HttpStatusCode.OK, grantAccessResponse);
return response;
}
}
GrantAccessRequest class:
public class GrantAccessRequest
{
public string DeviceId { get; set; }
}
Client:
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:55208/");
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
Uri uri = null;
var request = new GrantAccessRequest { DeviceId = "bla" };
var response = client.PostAsJsonAsync("api/accesspanel", uri).Result;
if (response.IsSuccessStatusCode)
{
uri = response.Headers.Location;
}
In my PostGrantAccess
method, grantAccessRequest
is constructed, but DeviceId
is null
Upvotes: 4
Views: 2348
Reputation: 1038710
Get rid of the [FromUri]
attribute on your controller action. Also on the client you don't seem to be doing anything with the request
variable which is containing the payload:
public HttpResponseMessage PostGrantAccess(GrantAccessRequest grantAccessRequest)
To better understand how model binding works in the Web API I recommend you reading the following article
.
So:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:55208/");
var request = new GrantAccessRequest { DeviceId = "bla" };
var response = client.PostAsJsonAsync("api/accesspanel", request).Result;
if (response.IsSuccessStatusCode)
{
var uri = response.Headers.Location;
}
}
Notice that you don't need to set the Accept
request header in this case because you are using the PostAsJsonAsync
method.
Also I don't know if this is a typo in your question but you seem to have specified api/accesspanel
as url whereas your controller action is called GrantAccessRequest
.
Upvotes: 5
Reputation: 1499860
Well this looks problematic to start with:
Uri uri = null;
var request = new GrantAccessRequest { DeviceId = "bla" };
var response = client.PostAsJsonAsync("api/accesspanel", uri).Result;
You're never doing anything with request
, and uri
will always be null. How are you expecting the device ID to make it through to the server?
(I confess I don't know enough about WebAPI to know exactly how you're expected to fix this, but presumably you want to use request
somewhere in the PostAsJsonAsync
call... Given the [FromUri]
attribute, I'd expect something to convert that data to part of the URI to use.)
Upvotes: 1