本文介绍了HttpClient的添加JSON认证头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与该LogMeIn的API认证的问题。
授权值是一个JSON对象。
当运行我的code,我碰上出现FormatException错误。

I am running into an issue with authentication for the LogMeIn api.The authorization value is a JSON object.When running my code, I run into FormatException error.

类型System.FormatException第一次机会异常出现在System.Net.Http.dll
其他信息:value的格式{companyId:9999999,PSK:o2ujoifjau3ijawfoij3lkas3l2}。无效

        var client = new HttpClient();
        client.BaseAddress = new Uri("http://secure.logmein.com/public-api/v1/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Add("Accept", "application/JSON; charset=utf-8");

        string s = "{\"companyId\":9999999,\"psk\":\"o2ujoifjau3ijawfoij3lkas3l2\"}";

        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(s);

       HttpResponseMessage response = client.GetAsync("authentication").Result;

应该如何格式化在这种情况下的授权密钥?

How should I be formatting the authorization key in this situation?

推荐答案

这会发生,因为LogMeIn的不喜欢用基本标准的认证模式。您应该添加邮件标题未经验证:

This happens, because LogMeIn does not use standard authentication schema like "Basic". You should add message header without validation:

string s = "{\"companyId\":9999999,\"psk\":\"o2ujoifjau3ijawfoij3lkas3l2\"}";
string h = "Authorization";

client.DefaultRequestHeaders.TryAddWithoutValidation(h, s);

请参阅和here

您可以检查您发送该请求在使用工具(网络调试器)正确的头一个名为Fiddler(这对于Web开发人员必须有工具)。
你需要下面的配置,以便通过提琴手代理加入到web.config中路由HTTP流量:

You can check that request you send have correct header using tool (web debugger) called Fiddler (It's a must have tool for web developer). You need to add the following configuration into web.config in order to route http traffic through Fiddler proxy:

<system.net>
   <defaultProxy>
       <proxy autoDetect="false" bypassonlocal="false" proxyaddress="http://127.0.0.1:8888" usesystemdefault="false" />
   </defaultProxy>
</system.net>

或请求intself指定它:

or specify it in a request intself:

client.Proxy = new Uri("http://localhost:8888/"); // default address of fiddler

这篇关于HttpClient的添加JSON认证头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 15:30