在ASP.NET中,httpContextBase对象、请求和User-Agent都可能为空,因此在代码中需要进行判断和处理。
以下是一个例子,通过判断httpContextBase是否为空来获取User-Agent:
public static string GetUserAgent(HttpContextBase httpContextBase)
{
if (httpContextBase != null && httpContextBase.Request != null && !string.IsNullOrEmpty(httpContextBase.Request.UserAgent))
{
return httpContextBase.Request.UserAgent;
}
else
{
return "unknown";
}
}
在这个例子中,我们首先判断httpContextBase对象是否为空,然后判断请求是否为空并且UserAgent是否为空,如果都不为空则返回UserAgent,否则返回“unknown”。