Putting a custom string in “Authorization” header in System.Net.HttpClient

僤鯓⒐⒋嵵緔 提交于 2019-12-08 20:16:16

问题


I am trying to use the System.Net.HttpClient class to post a message to Google Cloud Messaging.

Google Cloud Message requires you to include a header called "Authorization", in a format similar to this:

key=AIzaSyBxFuZ9IbtGbJHX6F5wdTc1mHnB7i0Lu8D

But the HttpClient class throws an exception when I try this.

string keyString = "key=AIzaSyBxFuZ9IbtGbJHX6F5wdTc1mHnB7i0LJ0w";
using (var client = new HttpClient())
{
    client.DefaultRequestHeaders.Add("Foo", keyString); // <== Proving I can
    client.DefaultRequestHeaders.Add("Authorization", keyString); // Exception thrown

The exception is of type System.FormatException. The message is

The format of value 'key=AIzaSyBxFuZ9IbtGbJHX6F5wdTc1mHnB7i0LJ0w' is invalid.

And the callstack is:

at System.Net.Http.Headers.HttpHeaderParser.ParseValue(String value, Object storeValue, Int32& index)
at System.Net.Http.Headers.HttpHeaders.ParseAndAddValue(String name, HeaderStoreItemInfo info, String value)
at System.Net.Http.Headers.HttpHeaders.Add(String name, String value)

How can I get this header into this post request without an exception being thrown?


Incidentally, I have composed a post like this using Fiddler, and it works:

Headers:

User-Agent: Fiddler
Authorization: key=AIzaSyBxFuZ9IbtGbJHX6F5wdTc1mHnB7i0Lu8D
Host: android.googleapis.com
Content-Length: 220
Content-Type: application/json

Request Body:

{
 "registration_ids" : ["APA91bEM6XPdiZv5VgNNApakfyYfZwB871018Hljl1L27kaPvksasnR0bHlmcCZFxOSPD6bDLMZgvgfT9xsKnF6Tg0oSQM2cMM1KRbuK7cR7jICqAnSDYg_SvERTzPMT8puXGTlVkEVH6dsneBkXiBu6pZikWXWyRATAVbXnAHTe20-nQerb0"],
}

回答1:


Try this answer instead:

https://stackoverflow.com/a/24575721/1981387

Seems like a bit of a workaround, since it's a string pair instead of a nice object, but it seems to work.




回答2:


That's because your value is breaking the HTTP specification.

The header should contain Authorization: scheme SPACE value as described here: http://www.ietf.org/rfc/rfc2617.txt

In your case:

Authorization: key AIzaSyBxFuZ9IbtGbJHX6F5wdTc1mHnB7i0Lu8D


来源:https://stackoverflow.com/questions/23535047/putting-a-custom-string-in-authorization-header-in-system-net-httpclient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!