Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 do I pass MyRequest to the calling method?

Currently, I have something like this

                var request = new MyRequest()
                    {
                        RequestId = Guid.NewGuid().ToString()
                    };

                var response = client.GetAsync("api/groups").Result;

How can I pass request to GetAsync?

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

var response = client.PostAsJsonAsync("api/groups", request).Result;
like image 359
Null Reference Avatar asked Sep 19 '13 05:09

Null Reference


People also ask

What is HttpClient GetAsync?

GetAsync(Uri, HttpCompletionOption) Send a GET request to the specified Uri with an HTTP completion option as an asynchronous operation. GetAsync(Uri, CancellationToken) Send a GET request to the specified Uri with a cancellation token as an asynchronous operation.

What is GetAsync C#?

The GetAsync method sends a GET request to the specified Uri as an asynchronous operation. The await operator suspends the evaluation of the enclosing async method until the asynchronous operation completes. When the asynchronous operation completes, the await operator returns the result of the operation, if any.


1 Answers

You cannot send a message body for HTTP GET requests and for that reason, you cannot do the same using HttpClient. However, you can use the URI path and the query string in the request message to pass data. For example, you can have a URI like api/groups/12345?firstname=bill&lastname=Lloyd and the 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 have to specify model binding like this.

public HttpResponseMessage GetGroups([FromUri]MyRequest myRequest)

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

like image 52
Badri Avatar answered Sep 28 '22 08:09

Badri