C# 带参数的 ASP.NET Web Api HttpClient.GetAsync

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18886626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:30:38  来源:igfitidea点击:

ASP.NET Web Api HttpClient.GetAsync with parameters

c#asp.netweb-servicesrestasp.net-web-api

提问by Null Reference

I have the following Web Api method signature

我有以下 Web Api 方法签名

public HttpResponseMessage GetGroups(MyRequest myRequest)

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

在客户端,如何将 MyRequest 传递给调用方法?

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 requestto GetAsync?

如何传递requestGetAsync

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

如果这是一种POST方法,我可以做这样的事情

var response = client.PostAsJsonAsync("api/groups", request).Result;

采纳答案by Badri

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=Lloydand the parameter class MyRequestlike this.

您不能为 HTTP GET 请求发送消息正文,因此,您不能使用HttpClient. 但是,您可以使用请求消息中的 URI 路径和查询字符串来传递数据。例如,您可以拥有像这样的 URIapi/groups/12345?firstname=bill&lastname=LloydMyRequest像这样的参数类。

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

Since MyRequestis a complex type, you have to specify model binding like this.

由于MyRequest是复杂类型,您必须像这样指定模型绑定。

public HttpResponseMessage GetGroups([FromUri]MyRequest myRequest)

Now, the MyRequestparameter will contain the values from the URI path and the query string. In this case, Idwill be 12345, FirstNamewill be bill and LastNamewill be Lloyd.

现在,该MyRequest参数将包含来自 URI 路径和查询字符串的值。在这种情况下,Id将是 12345,FirstName将是 billLastName并将是 Lloyd。