如何知道 HTTP 请求标头值是否存在

发布于 2024-09-15 23:06:50 字数 354 浏览 4 评论 0原文

我确信这很简单,但是却让我感到厌烦!我在Web应用程序中使用了一个组件,可以通过添加标题“ xyzcomponent = true”来识别自身,而我遇到的问题是,您如何在视图中检查一下?

以下内容不起作用:

if (Request.Headers["XYZComponent"].Count() > 0)

也不是这样:

if (Request.Headers.AllKeys.Where(k => k == "XYZComponent").Count() > 0)

如果未设置标头变量,两者都会抛出异常。任何帮助将不胜感激。

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?

The following wont work:

if (Request.Headers["XYZComponent"].Count() > 0)

Nor this:

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

冷弦 2024-09-22 23:06:51
if (Request.Headers["XYZComponent"].Count() > 0)

...将尝试计算返回字符串中的字符数,但如果标头不存在,它将返回 NULL,这就是它抛出异常的原因。你的第二个例子有效地做了同样的事情,它将搜索 headers 集合,如果不存在则返回 NULL,然后你尝试计算字符数:

使用这个:

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

或者如果你想处理空白或未设置空字符串,然后使用:

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

Null Coalesce 运算符 ??如果标头为 null,则返回一个空字符串,从而阻止抛出 NullReferenceException。

您的第二次尝试的变体也将起作用:

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

编辑:抱歉没有意识到您正在明确检查值true

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

如果标头值为 false,则将返回 false,或者如果 Header 尚未设置或者 Header 是除 true 或 false 之外的任何其他值。如果 Header 值为字符串 'true' 将返回 true

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'

素罗衫 2024-09-22 23:06:51

标头存在:

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

或者更好:

string xyzHeader = Request.Headers["XYZComponent"];
bool isXYZ;

if (bool.TryParse(xyzHeader, out isXYZ) && isXYZ)

这将检查它是否设置为 true。这应该是万无一失的,因为它不关心前导/尾随空格并且不区分大小写(bool.TryParse 可以在 null 上工作)

Addon:< /strong> 您可以使用返回可为空布尔值的扩展方法使这变得更简单。它应该适用于无效输入和空输入。

public static bool? ToBoolean(this string s)
{
    bool result;

    if (bool.TryParse(s, out result))
        return result;
    else
        return null;
}

用法(因为这是一个扩展方法而不是实例方法,所以不会在 null 上抛出异常 - 但它可能会令人困惑):

if (Request.Headers["XYZComponent"].ToBoolean() == true)

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)
九八野马 2024-09-22 23:06:51

首先,你认为你不会这样做。您可以在控制器中执行此操作,并将视图模型返回给视图,以便视图不需要关心自定义 HTTP 标头,而只需在视图模型上显示数据:

public ActionResult Index()
{
    var xyzComponent = Request.Headers["xyzComponent"];
    var model = new MyModel 
    {
        IsCustomHeaderSet = (xyzComponent != null)
    }
    return View(model);
}

Firstly you don't do this in your view. You do it in the controller and return a view model to the view so that the view doesn't need to care about custom HTTP headers but just displaying data on the view model:

public ActionResult Index()
{
    var xyzComponent = Request.Headers["xyzComponent"];
    var model = new MyModel 
    {
        IsCustomHeaderSet = (xyzComponent != null)
    }
    return View(model);
}
女中豪杰 2024-09-22 23:06:51

在 dotnet core 中,Request.Headers["X-MyCustomHeader"] 返回 StringValues,它不会为 null。您可以检查计数以确保它找到您的标头,如下所示:

var myHeaderValue = Request.Headers["X-MyCustomHeader"];
if(myHeaderValue.Count == 0) return Unauthorized();
string myHeader = myHeaderValue.ToString(); //For illustration purposes.

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.
黎歌 2024-09-22 23:06:51

以下代码应允许您检查您在 request.headers

if (Request.Headers.AllKeys.Contains("XYZComponent"))
{
    // Can now check if the value is true:
    var value = Convert.ToBoolean(Request.Headers["XYZComponent"]);
}

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"]);
}
青丝拂面 2024-09-22 23:06:51
if ((Request.Headers["XYZComponent"] ?? "") == "true")
{
    // header is present and set to "true"
}
if ((Request.Headers["XYZComponent"] ?? "") == "true")
{
    // header is present and set to "true"
}
私藏温柔 2024-09-22 23:06:51
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

或者

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
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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文