How to use the System.Net.HttpRequestHeader enumeration with an ASP.NET request?

In WCF (System.Net.WebHeaderCollection), the header value can be restored using either the System.Net.HttpRequestHeader enumeration or the header line:

WebOperationContext.Current.IncomingRequest.Headers[httpRequestHeaderEnum] 
// or
WebOperationContext.Current.IncomingRequest.Headers.Get(rawHeaderString)

But in ASP.NET, the headers are in the NameValueCollection, which only accepts the header line:

 HttpContext.Current.Request.Headers[rawHeaderString]

To use Enum for ASP.NET, where is the map from enum System.Net.HttpRequestHeader located in its header line?

+4
source share
3 answers

How about writing a matching method? For reference: listing the HttpRequestHeader

, Binary Worrier post, - :

public static string TranslateToHttpHeaderName(HttpRequestHeader enumToTranslate)
{
    const string httpHeaderNameSeparator = "-";
    string enumName = enumToTranslate.ToString();
    var stringBuilder = new StringBuilder();

    // skip first letter
    stringBuilder.Append(enumName[0]);
    for (int i = 1; i < enumName.Length; i++)
    {
        if (char.IsUpper(enumName[i])) stringBuilder.Append(httpHeaderNameSeparator);
        stringBuilder.Append(enumName[i]);
    }
    // Cover special case for 2 character enum name "Te" to "TE" header case.
    string headerName = stringBuilder.ToString();
    if (headerName.Length == 2) headerName = headerName.ToUpper();
    return headerName;
}
0

, WebHeaderCollection

    private static readonly ConcurrentDictionary<HttpRequestHeader, string> ToStringKeyCache = new ConcurrentDictionary<HttpRequestHeader, string>();
    public static string ToStringKey(this HttpRequestHeader enumToEvaluate)
    {
        var str = ToStringKeyCache.GetOrAdd(enumToEvaluate, header =>
        {
            var nm = new WebHeaderCollection();
            nm.Set(header, "X");
            return nm.AllKeys.Single();
        });
        return str;
    }
0

If I do not completely understand your question:

  • Import the namespace System.Net:using System.Net;

eg. WebForms:

using System.Net

protected void Page_Load(object sender, EventArgs e)
{
    //Single - e.g. Connection 
    FooLabel.Text = Request.Headers[HttpRequestHeader.Connection.ToString()] + "<hr />";

    //Go through all
    foreach (var en in Enum.GetNames(typeof(HttpRequestHeader)))
    {
        FooLabel.Text += en + " : " + Request.Headers[en] + "<br />";
    }
}

Hth ...

-1
source

All Articles