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
ASP.NET Web Api HttpClient.GetAsync with parameters
提问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 request
to GetAsync
?
如何传递request
到GetAsync
?
If it's a POST
method, 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=Lloyd
and the parameter class MyRequest
like this.
您不能为 HTTP GET 请求发送消息正文,因此,您不能使用HttpClient
. 但是,您可以使用请求消息中的 URI 路径和查询字符串来传递数据。例如,您可以拥有像这样的 URIapi/groups/12345?firstname=bill&lastname=Lloyd
和MyRequest
像这样的参数类。
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.
由于MyRequest
是复杂类型,您必须像这样指定模型绑定。
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.
现在,该MyRequest
参数将包含来自 URI 路径和查询字符串的值。在这种情况下,Id
将是 12345,FirstName
将是 billLastName
并将是 Lloyd。