WebRequest NET Core 3.1 中的自定义标头

问题描述

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

我的代码

Sub Remove_worksheets()
Dim A As workbook: Set A = Workbooks("A.xlsx")
Dim sh As Worksheet

Application.ScreenUpdating = False
Application.displayAlerts = False

For Each sh In A.Worksheets
    If sh.Range("D1").End(xlDown) < 2020 And sh.Range("E1").End(xlDown) < 9 Then
      sh.Delete
    End If
Next sh

Application.ScreenUpdating = True
Application.displayAlerts = True

End Sub

例外:

enter image description here

解决方法

让我们稍微浏览一下相关的源代码。在 System.txt 中有一个 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 定义在 Internallike this 中:

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

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