问题
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