如何将默认标题“授权”设置为一个值

时间:2019-04-05 15:11:06

标签: c# .net set authorization httpclient

我有一个访问rest api端点的HttpClient。对于此http请求,我必须将标题“ Authorization”设置为值“ ABCDE”。我已经尝试了几种方法,并通过“ Error Setting HttpHeader:Authorization:”将其出错。

第一行错误(Client.DefaultRequestHeaders.Add(“授权”,授权);):

2019-04-05 10:42:36.824: Error Setting HttpHeader: Authorization:

2019-04-05 10:42:36.854:    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)
   at ETICreditCardProcessorService.ImplementedHttpClient.SetAuthorizationHeader(String authorization) in BaseHttpClient.cs:line 66

第二行错误(Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(“”,授权);):

2019-04-05 10:58:01.872: Error Setting HttpHeader: Authorization:

2019-04-05 10:58:01.872:    at System.Net.Http.Headers.HeaderUtilities.CheckValidToken(String value, String parameterName)
   at System.Net.Http.Headers.AuthenticationHeaderValue..ctor(String scheme, String parameter)
   at ETICreditCardProcessorService.ImplementedHttpClient.SetAuthorizationHeader(String authorization) in BaseHttpClient.cs:line 67

两行代码都抛出错误。我想念什么吗?

感谢您的帮助 NH

public class ImplementedHttpClient : BaseHttpClient
{
        public void SetAuthorizationHeader(string authorization)
        {            
            //Client.DefaultRequestHeaders.Add("Authorization", authorization);            
            Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("", authorization);
        }

        public void SetContentType(string contentType)
        {
            Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(contentType));
        }
}

2 个答案:

答案 0 :(得分:1)

我找到了另一个方法TryAddWithoutValidation。 效果很好。

Client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", authorization); 

答案 1 :(得分:0)

尝试一下:

httpRequest.Headers.Add("Authorization", "ABCDE");