使用HttpClient调用时,带有uri参数的发布(或放置)请求不起作用 [英] Post (or put) request with uri parameter not working when calling with HttpClient
问题描述
在尝试使用c#制作Web API并通过c#HttpClient使用它时,我已经编写了一些控制器和客户端调用,并且工作正常,但是现在我需要使用两个参数(一个简单的值)调用Post方法(长)直接在URL [FromURI]中输入,另一个是在主体中传递的复杂类型。
In trying to make a Web API in c# and consume it via c# HttpClient, I've already written some controllers and client calls and is working fine, but now I need to call a Post method with two parameters, one simple value (long) directly in the URL[FromURI], and the another one is a complex type passed in body.
我想我可以简化答案,假设我只是想要调用帖子或放置URL中传递的一个简单参数。
I think I can simplify the answer, suppose I just want to call a post or put with one simple parameter passed in the URL.
首先,让我们看一下我的Web服务器映射配置:
First of all, lets see my web server mapping config:
HttpConfiguration config = new HttpConfiguration(); config.Routes.MapHttpRoute(
name: "DefaultWebApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional });
多数民众赞成在我的Put控制器:
And thats my Put controller:
[HttpPut]
public IHttpActionResult PutComandas([FromUri] long ticket)
{
...
}
我可以使用 PostMan 和类似 localhost:8200 / api / Comandas的URL毫无问题地调用它?ticket = 9 ,但是我找不到用HttpClient进行调用的方法,而且,令我感到奇怪的是,我不能简单地(在PostMan中)调用localhost:8200 / api / Comandas / 9正如我对get请求所做的那样...就像路由配置适用于gets,但不适用于puts / posts ...无论如何,真正的问题是:我找不到使用以下方法进行正确的put调用的方法HttpClient。我正在尝试:
I can call this without problem using PostMan and URL like localhost:8200/api/Comandas?ticket=9, but I can't find a way to do that call with HttpClient, also, it's strange to me that I can not simply call (in PostMan) to localhost:8200/api/Comandas/9 as I can do with get requests... is like the routing configuration is working for gets, but not for puts/posts... Anyway, the real problem is: I can't find the way to do a correct put call with HttpClient. I'm trying:
HttpClient client = new HttpClient();
var response = client.PutAsync("localhost:8200/api/Comandas?ticket=9", null).Result;
但我收到未找到的回复。
but I receive a Not Found response.
注意:我可以使用复杂的身体参数调用Put / Post,而不会出现问题。
Note: I can call Put/Post with complex body parameters without problems.
推荐答案
一种更干净的方法是使用字典并通过FormUrlEncodedContent
A cleaner way would be to use a Dictionary and pass as FormUrlEncodedContent
var url = "localhost:8200/api/Comandas";
var parameters = new Dictionary<string, string> { { "ticket", "9" } };
var encodedContent = new FormUrlEncodedContent(parameters);
var response = await client.PutAsync(url, encodedContent);
此外,HttpClient应该只实例化一次,然后重新使用: https:// docs .microsoft.com / en-us / dotnet / api / system.net.http.httpclient?view = netframework-4.7.1#备注
Also as a side note, HttpClient should only be instantiated once and then re-used: https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.7.1#Remarks
编辑:用户现在已澄清,他们正在同时寻找Uri参数和Body参数。从上面的代码继续:
User has now clarified they are looking for both a Uri param and a Body param. Following on from code above:
AddQueryString可通过
AddQueryString is available through
Microsoft.Owin.Infrastructure.WebUtilities.AddQueryString()
或者如果使用.NET Core
or if using .NET Core
Microsoft.AspNetCore.WebUtilities.QueryHelpers.AddQueryString()
var url = "localhost:8200/api/";
// Query string parameters
var parameters = new Dictionary<string, string>(){ { "ticket", "9" } };
// Create json for body
var content = new JObject(yourBodyObject);
// SetupHttpClient
client.BaseAddress = new Uri(url);
// This is the important bit
var requestUri = QueryHelpers.AddQueryString("Comandas", parameters);
var request = new HttpRequestMessage(HttpMethod.Put, requestUri);
// Setup headers for Content-Type
request.Headers.Add("Accept", "application/json");
// Add body content
request.Content = new StringContent(
content.ToString(),
Encoding.UTF8,
"application/json"
);
// Send the request
client.SendAsync(request);
这篇关于使用HttpClient调用时,带有uri参数的发布(或放置)请求不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!