问题描述
我敢肯定,这很简单,但把我逼疯了!我在 Web 应用程序中使用了一个组件,该组件在 Web 请求期间通过添加标头XYZComponent=true"来标识自己 - 我遇到的问题是,您如何在视图中检查这一点?
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 "XYZComponent=true" - the problem I'm having is, how do you check for this in your view?
以下方法不起作用:
if (Request.Headers["XYZComponent"].Count() > 0)
也不是这样:
if (Request.Headers.AllKeys.Where(k => k == "XYZComponent").Count() > 0)
如果尚未设置标头变量,则两者都会引发异常.任何帮助将不胜感激.
Both throw exceptions if the header variable has not been set. Any help would be most appreciated.
推荐答案
if (Request.Headers["XYZComponent"].Count() > 0)
... 将尝试计算返回字符串中的字符数,但如果标头不存在,它将返回 NULL,因此它抛出异常.您的第二个示例有效地执行了相同的操作,它将搜索 Headers 的集合,如果不存在则返回 NULL,然后您尝试计算其上的字符数:
... 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:
改用这个:
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)
空合并运算符 ??如果标头为空,将返回一个空白字符串,停止它抛出 NullReferenceException.
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")))
<小时>
很抱歉没有意识到您正在明确检查值 true:
Sorry didn't realise you were explicitly checking for the value true:
bool isSet = Boolean.TryParse(Request.Headers["XYZComponent"], out isSet) && isSet;
如果 Header 值为 false,或者 Header 尚未设置,或者 Header 是 true 或 false 以外的任何其他值,则将返回 false.会返回true就是Header值是字符串'true'
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'
这篇关于获取 Request.Headers 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!