WebApi服务器对IP地址黑名单限制
作者:C/S框架网  发布日期:2017-09-20 19:06:45
  WebApi服务器对IP地址黑名单限制


C# Code:

/// <summary>
/// IP地址黑名单限制
/// </summary>
public class IPBlacklistHandler : DelegatingHandler
{
   protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   {
      string IP = IPHelper.GetIPAddress(request);
      
      //检查黑名单
      string ErrorMsg = "";
      bool validate = !IP.IsNullOrEmpty() && Blacklist.ValidateIPAddress(IP, out ErrorMsg);
      
      if (validate == false)
      {
         return Task<HttpResponseMessage>.Factory.StartNew(() =>
         {
            ModelResponse response = new ModelResponse { Code = ErrorCodes.IPAddressAccessDenied, Message = ErrorCodes.IPAddressAccessDenied_Msg };
            return new HttpResponseMessage
            {
               Content = new StringContent(JsonConvert.SerializeObject(response), Encoding.GetEncoding("UTF-8"), "application/json")
               };
               });
            }
            else
            {
               return base.SendAsync(request, cancellationToken);
            }
         }
         
      }
      
      //来源:C/S框架网(www.csframework.com) QQ:1980854898
      

C# Code:

config.MessageHandlers.Add(new IPBlacklistHandler());

//来源:C/S框架网(www.csframework.com) QQ:1980854898


上一篇 下一篇