System.Web.NullPointerException
2024-09-19 22:05:10
在.Net异步webApi中我们需要记录日志信息,需要获取客户端的ip地址,我们需要使用:HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];来获取客户端的ip地址,在调用异步方法(wait Task.Run(() =>{ }))前需要将主线程中获取的HttpContext.Current对象存至缓存(Cache)中达到多线程共享的目的。如果不是通过主线程获取HttpContext.Current对象将会报空指针异常(NullPointerException)。
示例代码:
System.Web.HttpRuntime.Cache.Insert("context", System.Web.HttpContext.Current); //异步调用,HttpContext存入缓存线程共享
wait Task.Run(() =>{ });
工具类方法示例代码:
/// <summary>
/// 获取客户端IP地址(无视代理)
/// </summary>
/// <returns>若失败则返回回送地址</returns>
public static string GetHostAddress()
{ HttpContext httpContext = HttpContext.Current;
if (httpContext == null)
httpContext = HttpRuntime.Cache.Get("context") as HttpContext;
string userHostAddress = httpContext.Request.ServerVariables["REMOTE_ADDR"]; if (string.IsNullOrEmpty(userHostAddress))
{
if (httpContext.Request.ServerVariables["HTTP_VIA"] != null)
userHostAddress = httpContext.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString().Split(',')[].Trim();
}
if (string.IsNullOrEmpty(userHostAddress))
{
userHostAddress = httpContext.Request.UserHostAddress;
} //最后判断获取是否成功,并检查IP地址的格式(检查其格式非常重要)
if (!string.IsNullOrEmpty(userHostAddress) && IsIP(userHostAddress))
{
return userHostAddress;
}
return "127.0.0.1";
}
最新文章
- jsp页面显示问题
- How to stop pycharm show files in project in red color?
- SQLServer异步调用,批量复制
- IOS开发——01_第一个OC程序
- nutz的json视图
- Linux内核设计第三周——构造一个简单的Linux系统
- 前端AJAX传递数组给Springmvc接收处理
- [light oj 1013] Love Calculator
- android102 查询,插入联系人
- 以字符串形式读取github上.json文件
- [Linked List]Sort List
- SVN权限解析规则详解(转)
- git入门大全
- .net开源工作流引擎ccflow表单数据返回值Pop分组模式和表格模式对比
- 转载&;修改:赶集mysql军规
- 网址导航18A
- 异常处理汇总 ~ 修正果带着你的Code飞奔吧!
- shell编程中如何执行oracle语句
- C. Maximum Subrectangle
- 雷林鹏分享:C# 常量
热门文章
- ServerManager.exe 0xc0000135 应用程序错误
- nginx配置自签名https
- [技术博客]采用Bootstrap框架进行排版布局
- etcd启动报错:couldn&#39;t find local name ";default"; in the initial cluster configuration
- 荔枝派nano例子
- Jackson的基本用法与拓展
- 复制centos 后不能上网,处理办法
- 【HBase】HBase 单机版安装及使用
- Pi1-lite
- SpringMVC返回值响应