专业网站建设品牌,十四年专业建站经验,服务6000+客户--广州京杭网络
免费热线:400-683-0016      微信咨询  |  联系我们

webapi获取IP的方式

当前位置:网站建设 > 技术支持
资料来源:网络整理       时间:2023/2/14 1:11:26       共计:3633 浏览

using System.Net.Http;


public static class HttpRequestMessageExtensions

{

   private const string HttpContext = "MS_HttpContext";

   private const string RemoteEndpointMessage =

       "System.ServiceModel.Channels.RemoteEndpointMessageProperty";

   private const string OwinContext = "MS_OwinContext";


   public static string GetClientIpAddress(this HttpRequestMessage request)

   {

      // Web-hosting. Needs reference to System.Web.dll

      if (request.Properties.ContainsKey(HttpContext))

      {

          dynamic ctx = request.Properties[HttpContext];

          if (ctx != null)

          {

              return ctx.Request.UserHostAddress;

          }

      }


      // Self-hosting. Needs reference to System.ServiceModel.dll.

      if (request.Properties.ContainsKey(RemoteEndpointMessage))

      {

           dynamic remoteEndpoint = request.Properties[RemoteEndpointMessage];

           if (remoteEndpoint != null)

           {

               return remoteEndpoint.Address;

           }

       }


      // Self-hosting using Owin. Needs reference to Microsoft.Owin.dll.

      if (request.Properties.ContainsKey(OwinContext))

      {

          dynamic owinContext = request.Properties[OwinContext];

          if (owinContext != null)

          {

              return owinContext.Request.RemoteIpAddress;

          }

      }


       return null;

   }

}


References required:


   HttpContextWrapper - System.Web.dll

   RemoteEndpointMessageProperty - System.ServiceModel.dll

   OwinContext - Microsoft.Owin.dll (you will have it already if you use Owin package)



第二种:

((System.Web.HttpContextWrapper)Request.Properties["MS_HttpContext"]).Request.UserHostAddress;

版权说明:
本网站凡注明“广州京杭 原创”的皆为本站原创文章,如需转载请注明出处!
本网转载皆注明出处,遵循行业规范,如发现作品内容版权或其它问题的,请与我们联系处理!
欢迎扫描右侧微信二维码与我们联系。
·上一条:asp.net WebApi获取客户端IP地址(无视代理)nginx | ·下一条:自动强制释放内存的SQL脚本

Copyright © 广州京杭网络科技有限公司 2005-2025 版权所有    粤ICP备16019765号 

广州京杭网络科技有限公司 版权所有