Null property when retrieved from api website

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; } } 

Customer:

  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; } 

PostGrantAccess built in my PostGrantAccess method, but DeviceId is null

+4
source share
2 answers

Get rid of the [FromUri] attribute in your controller action. Also on the client, you seem to be doing nothing with the request variable, which contains the payload:

 public HttpResponseMessage PostGrantAccess(GrantAccessRequest grantAccessRequest) 

To better understand how model binding works in the web API, I recommend that you read 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; } } 

Note that you do not 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, while your controller action is called GrantAccessRequest .

+5
source

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 never do anything with request , and uri will always be null. How do you expect the device identifier to go to the server?

(I admit, I don’t know enough about WebAPI to know exactly how you should fix this, but presumably you want to use request somewhere in the call to PostAsJsonAsync ... Given the [FromUri] attribute, I would expect something to convert this data is part of the URI used.)

+1
source

All Articles