在.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";
}

System.Web.NullPointerException的更多相关文章

  1. 错误 1 类型“System.Web.Mvc.ModelClientValidationRule”同时存在于“c:\Progra

    问题如图: 解决办法: step1: 首先关闭你应用程序方案,在你保存项目的文件夹下找到ProjectName.csproj  ProjectName是你实际的应用程序名称. step2: 用文字编辑 ...

  2. 未能加载文件或程序集“System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35”或它的某一个依赖项。系统找不到指定的文件

    ASP.NET 运行时错误:针对类型System.Web.Mvc.PreApplicationStartCode的应用程序邓启动初始化方法Start 引发了异常,显示下列错误消息: 未能加载文件或程序 ...

  3. Could not load type 'System.Web.Mvc.ViewPage<dynamic>' in asp.net mvc2 after publishing the website

    在WebConfig里 找到 <pages></pages> <pages pageParserFilterType="System.Web.Mvc.ViewT ...

  4. System.Web.Http.Cors配置跨域访问的两种方式

    System.Web.Http.Cors配置跨域访问的两种方式 使用System.Web.Http.Cors配置跨域访问,众多大神已经发布了很多文章,我就不在详细描述了,作为小白我只说一下自己的使用心 ...

  5. System.Web.HttpRequestValidationException: A potentially dangerous Request.F

    ASP.NET .0验证请求 System.Web.HttpRequestValidationException: A potentially dangerous Request.F System.W ...

  6. MVC-命名空间“System.Web.Mvc”中不存在类型或命名空间名称“Html”(是否缺少程序集引用?)

    如上截图,明明引用了“System.web.mvc”,可是还出这样的错误. 解决方法: 1.右键引用的“System.Web.Mvc” 2.<复制本地>一样选择<True> 3 ...

  7. 如何解决System.Web.HttpRequestValidationException的异常

    在.net framework 4.0版本以下, 只需要在web.config中进行如下配置: <configuration>    <system.web>        & ...

  8. 未能加载文件或程序集“System.Web.DataVisualization...”

    启动web项目发现未能加载文件或程序集“System.Web.DataVisualization...” 这是因为项目bin目录缺少“System.Web.DataVisualization.dll” ...

  9. Mvc 之System.Web.Optimization 压缩合并如何让*.min.js 脚本不再压缩

    最近项目中用到了easy ui ,但是在配置BundleConfig 的时候出现了问题,easy ui的脚本jquery.easyui.min.js 压缩后出现各种脚本错误,总是莫名其妙的 i标量错误 ...

随机推荐

  1. Sequelize 数据类型

    Sequelize.STRING // VARCHAR(255)Sequelize.STRING(1234) // VARCHAR(1234)Sequelize.STRING.BINARY // VA ...

  2. [Beta阶段]第八次Scrum Meeting

    Scrum Meeting博客目录 [Beta阶段]第八次Scrum Meeting 基本信息 名称 时间 地点 时长 第八次Scrum Meeting 19/05/14 大运村寝室6楼 25min ...

  3. 如何在 Apache Hive 中解析 Json 数组

    我们都知道,Hive 内部提供了大量的内置函数用于处理各种类型的需求,参见官方文档:Hive Operators and User-Defined Functions (UDFs).我们从这些内置的 ...

  4. git clone或者git clone时遇到gnutls_handshake() failed: An unexpected TLS packet was received.如何处理?

    答: 直接将https修改为http即可, 如: $ git clone https://github.com/Jello_Smith/my-example.git ->  git clone ...

  5. sparkStreaming读取kafka写入hive表

    sparkStreaming: package hive import java.io.File import org.apache.kafka.clients.consumer.ConsumerRe ...

  6. FilelistCreator --- 导出文件列表神器 及其他好用工具

    https://www.sttmedia.com/ Standard Software WordCreator: Creates readable words, sentences or texts ...

  7. python bottle + jieba分词服务

    2019-12-16 19:46:34 星期一 最近接触到结巴分词项目, 就试试 用python的bottle库来当服务器监听localhost:8080 把请求的数据转给jieba来分词, 并返回分 ...

  8. git向远程git仓库提交代码步骤详解

    一.从远程仓库clone工程到本地 git clone -b 分支名称 http://10.1.1.11/service/tmall-service.git  localDestDirectory l ...

  9. syncronizationcontext

    FormDesign.cs       增加变量定义  public string testName { get; set; } TaskWrapper.cs string tmpTest = &qu ...

  10. js小数计算的问题,为什么0.1+0.2 != 0.3

    //下面可以用原生解决 0.1+0.2 的问题 parseFloat((0.1 + 0.2).toFixed(10)) 复制代码 console.log(0.1+0.2===0.3); //true ...