WebApi服务器对IP地址黑名单限制
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
/// <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
config.MessageHandlers.Add(new IPBlacklistHandler());
//来源:C/S框架网(www.csframework.com) QQ:1980854898
版权声明:本文为开发框架文库发布内容,转载请附上原文出处连接
NewDoc C/S框架网