How to get a null value if the header doesn't exist

和自甴很熟 提交于 2019-12-13 13:34:20

问题


I am using the request context to get the value of the header called "token".

 var token = context.request.Headers.GetValues("Token")

Now If the header exists. This all works hundreds, But now if the header doesn't exist, I want it to return null. But instead it throws an exception System.InvalidOperationExecption

Is my only option to throw a try catch around it?


回答1:


you can do this

if (Context.Request.Headers["Token"] != null)
{
      var token = Context.Request.Headers.GetValues("Token");         
      return token;
}
else 
      return null;



回答2:


Try using this:

 var token = string.IsNullOrEmpty(context.request.Headers.GetValues("Token")) ? null :
                               context.request.Headers.GetValues("Token");



回答3:


The Headers class provides a Contains() method.

Example 1:

if (!request.Headers.Contains("Token"))
    {
        return null;
    }

Example 2:

string token = request.Headers.Contains("Token") ? request.Headers.GetValues("Token").First() : null;



回答4:


You could use the Try Catch logic:

try
{
    var token = context.request.Headers.GetValues("Token");
}

catch
{
    var token = null;
}


来源:https://stackoverflow.com/questions/22320944/how-to-get-a-null-value-if-the-header-doesnt-exist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!