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;
  • 相关阅读:
    记第一场省选
    POJ 2083 Fractal 分形
    CodeForces 605A Sorting Railway Cars 思维
    FZU 1896 神奇的魔法数 dp
    FZU 1893 内存管理 模拟
    FZU 1894 志愿者选拔 单调队列
    FZU 1920 Left Mouse Button 简单搜索
    FZU 2086 餐厅点餐
    poj 2299 Ultra-QuickSort 逆序对模版题
    COMP9313 week4a MapReduce
  • 原文地址:https://www.cnblogs.com/jimcsharp/p/5519245.html
Copyright © 2011-2022 走看看