【问题标题】:HttpClient Authorization Header Invalid FormatHttpClient 授权标头格式无效
【发布时间】:2018-04-13 14:09:02
【问题描述】:

当我尝试使用下面的地址和授权值发出GET 请求时,我没有问题。

地址:http://example.com/xyz.svc/branches/?latitude=0&longitude=0&range=20000

标题键:授权

值:示例;foo

当我尝试使用 HttpCLient 时,我得到授权标头值的格式无效错误

我就是这样尝试的

HttpClient client = new HttpClient();

    string latitude = "0";
    string longitude = "0";
    string range = "2000";

    string uri = "/xyz.svc/branches/?latitude=0&longitude=0&range=20000;

    string value = "foo";

    client.BaseAddress = new Uri("http://example.com");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(
        new MediaTypeWithQualityHeaderValue("application/json"));
    client.DefaultRequestHeaders.Add("Authorization", String.Format("example;{0}", value));

    HttpResponseMessage response = await client.GetAsync(uri);

    var responseJson = await response.Content.ReadAsStringAsync();

    Console.WriteLine(responseJson);

我做错了什么?

【问题讨论】:

  • 如果您提供这样的授权会发生什么?我就是这样做的:client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes("example;foo")));
  • 它的 : 不是 ; 顺便说一句。
  • @Alex K,如果您指的是授权值,它是;就我而言。它在一个字符串中

标签: c# authorization dotnet-httpclient


【解决方案1】:

通常,授权标头的格式为{scheme} {token},这是它试图用您当前的代码验证的格式。

有些服务器可以配置为接受不同的格式。为避免客户端验证标准格式,请使用TryAddWithoutValidation

client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", String.Format("example;{0}", value));

根据您的示例将具有以下请求标头

Accept application/json
Authorization example;foo

【讨论】:

  • 对于任何尝试使用 google 的 key=blahblahblahblah 格式的人来说,这都是完美的!
  • 谢谢亲爱的耶稣。我无法告诉你验证有多烦人,我一直在与需要格式的服务交互,“授权:代码”没有领域。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多