Search code examples
c#http-headershttpwebrequestasp.net-core-3.1argumentexception

Custom headers in WebRequest NET Core 3.1


I'm trying to perform a web request from the client (NET Core 3.1) to a server. But I'm getting an error when passing custom information in headers. Please, I would like to know how to pass the information in the header. Thanks.

My code:

var request = (HttpWebRequest)WebRequest.Create("https://localhost:44351/mycontroller");
var postData = "n=42&s=25";
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
request.Headers["X‐test"] = "884436999";

The exception:

enter image description here


Solution

  • Let's take a little tour at the related source code. In System.txt there is a row:

    net_WebHeaderInvalidHeaderChars=Specified value has invalid HTTP Header characters.
    

    That means we should look for this net_WebHeaderInvalidHeaderChars key in the source code of WebHeaderCollection:

    //
    // CheckBadChars - throws on invalid chars to be not found in header name/value
    //
    internal static string CheckBadChars(string name, bool isHeaderValue) {
    
        ...
    
        if (isHeaderValue) {
            ...
        }
        else {
            // NAME check
            //First, check for absence of separators and spaces
            if (name.IndexOfAny(ValidationHelper.InvalidParamChars) != -1) {
                throw new ArgumentException(SR.GetString(SR.net_WebHeaderInvalidHeaderChars), "name");
            }
            
            ...
        }
        return name;
    }
    

    This means that the error is thrown if the provided name contains some invalid characters.

    The InvalidParamChars are defined inside the Internal class like this:

    internal static readonly char[]  InvalidParamChars =
        new char[]{
        '(',
        ')',
        '<',
        '>',
        '@',
        ',',
        ';',
        ':',
        '\\',
        '"',
        '\'',
        '/',
        '[',
        ']',
        '?',
        '=',
        '{',
        '}',
        ' ',
        '\t',
        '\r',
        '\n'};
    

    So, all you have to do is to make sure that the request header name does not contain any of the not allowed characters.