web api 根据ip 限制在一定时间内.疯狂访问 api

api  可以是web 也可以是宿主self .(参照上篇文章)

2种获取ip方式不同

 web获取方式 :

if (request.Properties.ContainsKey["MS_HttpContext"])
{
var ctx = request.Properties["MS_HttpContext"] as HttpContextWrapper;
if (ctx != null)
{
var ip = ctx.Request.UserHostAddress;
}
}

self 获取ip

if (request.Properties.ContainsKey[RemoteEndpointMessageProperty.Name]) 
{
    var remote = request.Properties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;

    if (remote != null)
    {
        var ip = remote.Address;
        //do stuff with IP
    }
}

可以封装成一个方法..扩展方法

public static class HttpRequestMessageExtensions
{
private const string HttpContext = "MS_HttpContext";
private const string RemoteEndpointMessage = "System.ServiceModel.Channels.RemoteEndpointMessageProperty";
public static string GetClientIpAddress(this HttpRequestMessage request)
{
if (request.Properties.ContainsKey(HttpContext))
{
dynamic ctx = request.Properties[HttpContext];
if (ctx != null)
{
return ctx.Request.UserHostAddress;
}
}
if (request.Properties.ContainsKey(RemoteEndpointMessage))
{
dynamic remoteEndpoint = request.Properties[RemoteEndpointMessage];
if (remoteEndpoint != null)
{
return remoteEndpoint.Address;
}
}
return null;
}
}

 

  新建一个 MyHandler  继承   : DelegatingHandler

 public class MyHandler : DelegatingHandler
    {
        protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var ip = request.GetClientIpAddress();
            Debug.WriteLine(ip);

                if (ip == null)
                {
                    return ToResponse(request, HttpStatusCode.Forbidden, "ip no found");
                } 
                return base.SendAsync(request, cancellationToken); 
        }

        private static Task ToResponse(HttpRequestMessage request, HttpStatusCode code, string message)
        {
            var tsc = new TaskCompletionSource();

            var response = request.CreateResponse(code);
            response.ReasonPhrase = message;
            response.Content = new StringContent(message);

            tsc.SetResult(response);

            return tsc.Task;
        } 
    }

然后在 WebApiConfig 注册下

    public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.MessageHandlers.Add(new MyHandler());
           
            config.EnableSystemDiagnosticsTracing();
        }

 

 

 

 

 

 

 

 


你可能感兴趣的:(web api 根据ip 限制在一定时间内.疯狂访问 api)