嗨,所有热心的程序员。我正在从一个C#客户端调用一个web项目,代码如下所示
private const string Url = "http://localhost:61809/";
public ItemService()
{
_httpClient.DefaultRequestHeaders.Accept.Clear();
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
public async Task<IEnumerable<Item>> GetItemsAsync(string searchString)
{
List<Items> = null;
string path = @"api/item/" + searchString;
HttpResponseMessage response = await _httpClient.GetAsync(Url+path).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
items = await response.Content.ReadAsAsync<List<Item>>().ConfigureAwait(false);
}
return items;
}一切正常,但如果对包含字符#的项进行照顾,则会失败。如果我查找项目,即掌握C#,它就失败了。我也在后端进行了调试,后端的内容不包含字符#。内容是掌握C,当然失败了。同样的情况发生,如果我从邮递员那里发出请求,我能做些什么来使它工作呢?后端代码的一些特殊编码或配置?
发布于 2017-03-31 13:22:34
是的,你确实需要对它进行编码。我正在编写正确的图书馆,但是它还没有发布。
同时,您可以使用百分比编码:
public class UrlEncoding
{
public static Encoding Utf8EncodingWithoutBom { get; } = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
public static string PercentEncodePathSegment(string value)
{
var bytes = Utf8EncodingWithoutBom.GetBytes(value);
var sb = new StringBuilder(bytes.Length);
foreach (var ch in bytes)
{
if (ch == '-' || ch == '.' || ch == '_' || ch == '~' ||
(ch >= '0' && ch <= '9') ||
(ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'Z') ||
ch == '!' || ch == '$' || ch == '&' || ch == '\'' ||
ch == '(' || ch == ')' || ch == '*' || ch == '+' ||
ch == ',' || ch == ';' || ch == '=' ||
ch == ':' || ch == '@')
{
sb.Append((char)ch);
}
else
{
sb.Append("%" + ch.ToString("X2", CultureInfo.InvariantCulture));
}
}
return sb.ToString();
}
}https://stackoverflow.com/questions/43140705
复制相似问题