Search code examples
c#.netsetauthorizationhttpclient

How to set Default Header "Authorization" to a value


I have an HttpClient that accesses a rest api endpoint. For this http request, I have to set the header "Authorization" to a value "ABCDE". I have tried it a couple of ways and its erroring out with "Error Setting HttpHeader: Authorization:"

First line Error(Client.DefaultRequestHeaders.Add("Authorization", authorization);):

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

Second Line Error(Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("", authorization);):

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

Both lines of code are throwing errors. Am I missing something?

Thanks for any help 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));
        }
}

Solution

  • try this:

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