ASP.NET Web Api HttpClient.GetAsync with parameters

I have the following Web Api method signature

public HttpResponseMessage GetGroups(MyRequest myRequest) 

In the client, how to pass MyRequest to the calling method?

I currently have something like this

  var request = new MyRequest() { RequestId = Guid.NewGuid().ToString() }; var response = client.GetAsync("api/groups").Result; 

How to pass request to GetAsync ?

If it's a POST method, I can do something like this

 var response = client.PostAsJsonAsync("api/groups", request).Result; 
+7
c # rest web-services asp.net-web-api
source share
1 answer

You cannot send a message body for HTTP GET requests, and for this reason you cannot do the same with HttpClient . However, you can use the URI path and query string in the query message to transfer data. For example, you can have a URI like api/groups/12345?firstname=bill&lastname=Lloyd and a parameter class MyRequest like this.

 public class MyRequest { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } 

Since MyRequest is a complex type, you must specify a model binding like this.

 public HttpResponseMessage GetGroups([FromUri]MyRequest myRequest) 

Now, the MyRequest parameter will contain values ​​from the URI path and the query string. In this case, Id would be 12345, FirstName would be the score, and LastName would be Lloyd.

+12
source

All Articles