获得一个Request.Headers值 [英] Getting a Request.Headers value

查看:1780
本文介绍了获得一个Request.Headers值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很简单,我敢肯定,但推动我逼疯了!还有就是我在Web应用程序中,通过添加标题XYZComponent =真正的一个Web请求期间识别自身的组件 - ?我有是,你如何在您的视图检查这个问题。

以下不会工作:

 如果(Request.Headers [XYZComponent] COUNT()方式> 0)

这也不:

 如果(Request.Headers.AllKeys.Where(K =方式>满足K ==XYZComponent)计数()0)

两者抛出异常,如果标题变量尚未设置。任何帮助将是最AP preciated。


解决方案

 如果(Request.Headers [XYZComponent] COUNT()方式> 0)

...将试图计算在返回字符串中的字符数,但如果标题不存在,将返回NULL,因此为什么它抛出一个异常。你的第二个例子有效地做同样的事情,它将通过标题集合搜索和​​返回NULL,如果不存在的话,你再试图指望字符的数目:

使用这个代替:

 如果(Request.Headers [XYZComponent]!= NULL)

或者,如果你想治疗空白或空的字符串作为没有设置,使用方法:

  IF((Request.Headers [XYZComponent] ??).Trim()长度方式> 0)

在空凝聚运营商?如果标题是空,停止它抛出一个NullReferenceException会返回一个空字符串。

你的第二次尝试的变化也将工作:

 如果(Request.Headers.AllKeys.Any(K => k ==XYZComponent))


编辑:对不起,不知道你是明确检查值的真正的:

 布尔使用isset = Boolean.TryParse(Request.Headers [XYZComponent],出使用isset)?使用isset:假的;

将返回false,如果头值是假的,或者如果头没有设置或者如果头比真或假的其他任何其他值。将返回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?

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.

解决方案

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 => 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 : false;

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值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆