WebRequest NET Core 3.1 中的自定义 headers

Custom headers in WebRequest NET Core 3.1

我正在尝试执行从客户端 (NET Core 3.1) 到服务器的 Web 请求。但是在 headers 中传递自定义信息时出现错误。 拜托,我想知道如何传递 header 中的信息。 谢谢

我的代码:

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";

异常:

让我们浏览一下相关的源代码。在 System.txt there is a row:

net_WebHeaderInvalidHeaderChars=Specified value has invalid HTTP Header characters.

这意味着我们应该在WebHeaderCollection的源代码中寻找这个net_WebHeaderInvalidHeaderChars键:

//
// 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 如果提供的 name 包含一些无效字符,则会抛出错误。

InvalidParamChars 定义在 Internal class like this:

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

因此,您所要做的就是确保请求 header 名称不包含任何不允许的字符。