Tag Archives: HttpClient HttpRequestHeaders.From Error

[Solved] HttpClient HttpRequestHeaders.From Error: The specified value is not a valid ‘From’ header string.

Preface

Reason for error: From needs to be the format of the email address.

Protocol header illustrate Example state
From Email address of the user who initiated this request From: [email protected] fixed

 

Code

            HttpRequestMessage httpRequestMessage = new HttpRequestMessage();
            httpRequestMessage.Headers.Add("from", "mywork");
            httpRequestMessage.Headers.Add("timestamp", timestamp);
            httpRequestMessage.Headers.Add("signature", signature);
            httpRequestMessage.Headers.Add("client-name", client_name);
            httpRequestMessage.Method = HttpMethod.Get;
            httpRequestMessage.RequestUri = new Uri(Domain + requestUrl);

            HttpResponseMessage response = await _client.SendAsync(httpRequestMessage);

            string r = string.Empty;

            if (response.IsSuccessStatusCode)
                r = await response.Content.ReadAsStringAsync();

            return r;

Error Messages:

The format of value 'mywork' is invalid.

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

 

Solution:

No suitable processing method has been found at present, temporarily use HttpWebRequest request

        public static string HttpGet(string url, string Accept, string ContentType, Dictionary<string, string> headers)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";

            if (Accept.NotEmpty())
                request.Accept = Accept;

            if (ContentType.NotEmpty())
                request.ContentType = ContentType;

            if (headers != null)
                foreach (KeyValuePair<string, string> item in headers)
                {
                    request.Headers.Add(item.Key, item.Value);
                }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }
        }