从代码调用Web资源时的常见任务是构建查询字符串以包含所有必需参数.虽然无论如何都没有火箭科学,但是你需要注意一些漂亮的细节,&如果不是第一个参数,编码参数等.
这样做的代码非常简单,但有点单调乏味:
StringBuilder SB = new StringBuilder();
if (NeedsToAddParameter A)
{
SB.Append("A="); SB.Append(HttpUtility.UrlEncode("TheValueOfA"));
}
if (NeedsToAddParameter B)
{
if (SB.Length>0) SB.Append("&");
SB.Append("B="); SB.Append(HttpUtility.UrlEncode("TheValueOfB")); }
}
Run Code Online (Sandbox Code Playgroud)
这是一个常见的任务,人们期望实用程序类存在,使其更加优雅和可读.扫描MSDN,我找不到一个 - 这让我想到了以下问题:
你知道做上述事情最干净的方式是什么?
我知道我能做到这一点
var nv = HttpUtility.ParseQueryString(req.RawUrl);
Run Code Online (Sandbox Code Playgroud)
但有没有办法将其转换回网址?
var newUrl = HttpUtility.Something("/page", nv);
Run Code Online (Sandbox Code Playgroud) 如何设置.NET HttpClient.SendAsync()请求以包含查询字符串参数和JSON正文(在POST的情况下)?
// Query string parameters
var queryString = new Dictionary<string, string>()
{
{ "foo", "bar" }
};
// Create json for body
var content = new JObject(json);
// Create HttpClient
var client = new HttpClient();
client.BaseAddress = new Uri("https://api.baseaddress.com/");
var request = new HttpRequestMessage(HttpMethod.Post, "something");
// Setup header(s)
request.Headers.Add("Accept", "application/json");
// Add body content
request.Content = new StringContent(
content.ToString(),
Encoding.UTF8,
"application/json"
);
// How do I add the queryString?
// Send the request
client.SendAsync(request);
Run Code Online (Sandbox Code Playgroud)
我见过的每个例子都说要设置
request.Content = new FormUrlEncodedContent(queryString) …Run Code Online (Sandbox Code Playgroud) 我想更改我写笔记的页面上的查询字符串。当我保存笔记时,我希望查询字符串具有该笔记的条目。因此,在初始保存后,用户可以根据查询字符串进行更新。但是要更新查询字符串,我需要进行完整的回发。反正有没有像这样更改查询字符串?
我试图将查询字符串传递到 BaseAddress 但它无法识别引号“?”。
引用破坏了 URI
首先我创建我的 BaseAddress
httpClient.BaseAddress = new Uri($"https://api.openweathermap.org/data/2.5/weather?appid={Key}/");
Run Code Online (Sandbox Code Playgroud)
然后我调用 GetAsync 方法,尝试添加另一个参数
using (var response = await ApiHelper.httpClient.GetAsync("&q=mexico"))....
Run Code Online (Sandbox Code Playgroud)
这是代码调用的 URI
https://api.openweathermap.org/data/2.5/&q=mexico
Run Code Online (Sandbox Code Playgroud) 我在不同的地方有一些代码,我有一个Dictionary<string,string>包含参数需要在查询字符串上.我有一些自己的代码用于格式化,以便它可以添加到URL的末尾.这个库里面有什么内容可以帮我吗?
c# ×6
asp.net ×3
url ×2
.net ×1
ajax ×1
asp.net-core ×1
httpclient ×1
javascript ×1
query-string ×1
url-encoding ×1