簡體   English   中英

為Web-API項目發送特殊字符

[英]Sending special character for a web-api project

大家好,熱情的程序員們。 我正在從C#客戶端向Web-api項目進行get調用,代碼如下所示

    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,這當然會失敗。 如果我從郵遞員發送了請求,也會發生同樣的事情,我該怎么辦才能使它起作用? 后端代碼的一些特殊編碼或配置?

是的,您確實需要對其進行編碼。 我正在編寫一個可以正確執行此操作的庫 ,但尚未發布。

同時,您可以這樣使用百分比編碼:

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();
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM