0

I want to add custom HTTP Header(hashed and signed) encoded in utf8 encoding (Encoding.UTF8.GetString). When the data is POSTed to IIS, Bad Request(400) error is encountered.

If the custom HTTP Header is encoded in base64 encoding, and there's no problem. But our partner is insisting to use utf8 encoding.

I want to know whether this "Bad Request(400)" is only caused by IIS?

And here is the code:

    var client = new HttpClient();
    client.DefaultRequestHeaders.Accept.Add(new 
    MediaTypeWithQualityHeaderValue("application/json"));
    HttpRequestMessage msg = new HttpRequestMessage(HttpMethod.Post, 
             "https://putsreq.com/AIWKVacHh2ok5FMGFpEg");
    var reqBody = "{'hello': 'world'}";
    msg.Content = new StringContent(reqBody);
    msg.Content.Headers.ContentType = new 
         MediaTypeWithQualityHeaderValue("application/json");
    var signature = SignMessage(reqBody); //hash and sign the message using 
                                          //private key
    var signatureString = Encoding.UTF8.GetString(signature); 
    msg.Headers.Add("signature", signature);
    try{
        var response = await client.SendAsync(msg);
        response.EnsureSuccessStatusCode();
        //Continue if success
   }catch(Exception ex){
        Trace.WriteLine("Exception: " + ex);
   }
4
  • 1
    Can you show us the way how you construct and send your custom header? Commented Aug 28, 2018 at 9:28
  • 1
    "Our partner is insisting to use UTF8 encoding" is a red flag. UTF8 data might contain invalid characters for headers, which can be the cause of 400, tools.ietf.org/html/rfc7231#section-6.5.1 You can capture the request and analyze (developer tools of your browser, or Fiddler, or Wireshark). Base64, contrarily, is the safe way to go. Commented Aug 28, 2018 at 12:16
  • @thehennyy I've updated the question with the code. Commented Aug 29, 2018 at 2:06
  • @LexLi Thanks for the info. Can you edit your comment as the answer? Commented Aug 29, 2018 at 2:07

1 Answer 1

1

Copied from comment.

HTTP headers have strict rules on what characters can appear,

https://www.rfc-editor.org/rfc/rfc7231#section-6.5.1

UTF8 data might contain invalid characters for headers, which can trigger such 400 errors. You can capture the request and analyze (developer tools of your browser, or Fiddler, or Wireshark).

Base64, contrarily, is the safe way to go. And standards like Basic authentication do use Base64 to encode user credentials.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.