Are there any constants for the default HTTP headers?

后端 未结 8 843
时光说笑
时光说笑 2021-02-01 00:21

Has Microsoft created a class full of constants for the standard HTTP header names or will I have to write my own?

8条回答
  •  旧时难觅i
    2021-02-01 01:10

    If you're using .NET Framework (not .NET Core), you can create an extension method to properly format the System.Net.HttpRequestHeader enum:

    using System;
    using System.Net;
    using System.Text;
    
    namespace YourNamespace
    {
       public static class HttpRequestHeaderEx
       {
          public static string ToStandardName(this HttpRequestHeader requestHeader)
          {
             string headerName = requestHeader.ToString();
    
             var headerStandardNameBuilder = new StringBuilder();
             headerStandardNameBuilder.Append(headerName[0]);
    
             for (int index = 1; index < headerName.Length; index++)
             {
                char character = headerName[index];
                if (char.IsUpper(character))
                {
                   headerStandardNameBuilder.Append('-');
                }
    
                headerStandardNameBuilder.Append(character);
             }
    
             string headerStandardName = headerStandardNameBuilder.ToString();
    
             return headerStandardName;
          }
       }
    }
    

    Usage:

       var userAgentHeaderName = HttpRequestHeader.UserAgent.ToStandardName();
    

提交回复
热议问题