zoukankan      html  css  js  c++  java
  • webapi获取请求地址的IP

    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;
  • 相关阅读:
    近期简单题炸分总结
    传输层中的端口号
    TCP的三次握手与四次挥手
    ppq的面试题总结
    一个C++源文件从文本到可执行文件经历的过程
    C++中的&符号的运用:引用、取地址和右值引用
    C++中的拷贝构造、赋值构造函数
    C++中的虚函数
    函数指针与回调函数
    C++中的智能指针
  • 原文地址:https://www.cnblogs.com/jimcsharp/p/5519245.html
Copyright © 2011-2022 走看看