发布:2022/10/18 17:56:35作者:管理员 来源:本站 浏览次数:705
使用webapi时有时会为了数据安全性加以访问者ip验证,就需要在API项目中进行处理
获取访问者IP地址 代码直接上 不罗嗦
/// <summary>
/// 获取访问者IP地址
/// </summary>
/// <returns></returns>
public static string GetHostAddress()
{
string userIP = "127.0.0.1";
try
{
if (System.Web.HttpContext.Current == null || System.Web.HttpContext.Current.Request == null || System.Web.HttpContext.Current.Request.ServerVariables == null)
return "";
string CustomerIP = "";
//CDN加速后取到的IP
CustomerIP = System.Web.HttpContext.Current.Request.Headers["Cdn-Src-Ip"];
if (!string.IsNullOrEmpty(CustomerIP))
{
return CustomerIP;
}
CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!String.IsNullOrEmpty(CustomerIP))
return CustomerIP;
if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
{
CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (CustomerIP == null)
CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
else
{
CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
if (string.Compare(CustomerIP, "unknown", true) == 0)
return System.Web.HttpContext.Current.Request.UserHostAddress;
return CustomerIP;
}
catch { }
return userIP;
}
/// <summary>
/// 检查IP地址格式
/// </summary>
/// <param name="ip"></param>
/// <returns></returns>
public static bool IsIP(string ip)
{
return System.Text.RegularExpressions.Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
}
给WebAPI 添加过滤
public class CheckSecurityFilter : AuthorizeAttribute
{
private HttpContext Context
{
get { return HttpContext.Current; }
}
public override void OnAuthorization(HttpActionContext actionContext)
{
//检查IP
if (!CheckIP())
{
HandleUnauthorizedRequest(actionContext);
Context.Response.Write("当前IP没有权限!");
Context.Response.End();
}
}
}
© Copyright 2014 - 2024 柏港建站平台 ejk5.com. 渝ICP备16000791号-4