Getting a Request.Headers value

后端 未结 7 1030
忘了有多久
忘了有多久 2020-12-01 07:33

Very simple I\'m sure, but driving me up the wall! There is a component that I use in my web application that identifies itself during a web request by adding the header \"X

相关标签:
7条回答
  • 2020-12-01 08:03

    Header exists:

    if (Request.Headers["XYZComponent"] != null)
    

    or even better:

    string xyzHeader = Request.Headers["XYZComponent"];
    bool isXYZ;
    
    if (bool.TryParse(xyzHeader, out isXYZ) && isXYZ)
    

    which will check whether it is set to true. This should be fool-proof because it does not care on leading/trailing whitespace and is case-insensitive (bool.TryParse does work on null)

    Addon: You could make this more simple with this extension method which returns a nullable boolean. It should work on both invalid input and null.

    public static bool? ToBoolean(this string s)
    {
        bool result;
    
        if (bool.TryParse(s, out result))
            return result;
        else
            return null;
    }
    

    Usage (because this is an extension method and not instance method this will not throw an exception on null - it may be confusing, though):

    if (Request.Headers["XYZComponent"].ToBoolean() == true)
    
    0 讨论(0)
  • 2020-12-01 08:04

    In dotnet core, Request.Headers["X-MyCustomHeader"] returns StringValues which will not be null. You can check the count though to make sure it found your header as follows:

    var myHeaderValue = Request.Headers["X-MyCustomHeader"];
    if(myHeaderValue.Count == 0) return Unauthorized();
    string myHeader = myHeaderValue.ToString(); //For illustration purposes.
    
    0 讨论(0)
  • 2020-12-01 08:08
    string strHeader = Request.Headers["XYZComponent"]
    bool bHeader = Boolean.TryParse(strHeader, out bHeader ) && bHeader;
    
    if "true" than true
    if "false" or anything else ("fooBar") than false
    

    or

    string strHeader = Request.Headers["XYZComponent"]
    bool b;
    bool? bHeader = Boolean.TryParse(strHeader, out b) ? b : default(bool?);
    
    if "true" than true
    if "false" than false
    else ("fooBar") than null
    
    0 讨论(0)
  • 2020-12-01 08:17
    if ((Request.Headers["XYZComponent"] ?? "") == "true")
    {
        // header is present and set to "true"
    }
    
    0 讨论(0)
  • 2020-12-01 08:18

    The following code should allow you to check for the existance of the header you're after in Request.Headers:

    if (Request.Headers.AllKeys.Contains("XYZComponent"))
    {
        // Can now check if the value is true:
        var value = Convert.ToBoolean(Request.Headers["XYZComponent"]);
    }
    
    0 讨论(0)
  • 2020-12-01 08:22
    if (Request.Headers["XYZComponent"].Count() > 0)
    

    ... will attempted to count the number of characters in the returned string, but if the header doesn't exist it will return NULL, hence why it's throwing an exception. Your second example effectively does the same thing, it will search through the collection of Headers and return NULL if it doesn't exist, which you then attempt to count the number of characters on:

    Use this instead:

    if(Request.Headers["XYZComponent"] != null)
    

    Or if you want to treat blank or empty strings as not set then use:

    if((Request.Headers["XYZComponent"] ?? "").Trim().Length > 0)
    

    The Null Coalesce operator ?? will return a blank string if the header is null, stopping it throwing a NullReferenceException.

    A variation of your second attempt will also work:

    if (Request.Headers.AllKeys.Any(k => string.Equals(k, "XYZComponent")))
    

    Edit: Sorry didn't realise you were explicitly checking for the value true:

    bool isSet = Boolean.TryParse(Request.Headers["XYZComponent"], out isSet) && isSet;
    

    Will return false if Header value is false, or if Header has not been set or if Header is any other value other than true or false. Will return true is the Header value is the string 'true'

    0 讨论(0)
提交回复
热议问题