public class AuthorizeAttrbute : System.Web.Http.Filters.AuthorizationFilterAttribute
{
public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
{
var ipAddress = GetIpAddress(); // 获取用户ip
object objCache = null;
objCache = GetCache(ipAddress); // 获取缓存结果
{
if (objCache == null)
{
if (!IpConfig(ipAddress))
{
//返回401
actionContext.Response = new HttpResponseMessage
{
Content = new StringContent("当前ip地址 " + ipAddress + " 无访问权限",
Encoding.GetEncoding("UTF-8"), "application/json"),
StatusCode = HttpStatusCode.Unauthorized
};
return;
}
else
{
SetCache(ipAddress, "1", 12); // Key,Value,失效时间
}
}
}
base.OnAuthorization(actionContext);
}
public static bool IpConfig(string ip)
{
// 返回 ip 地址在白名单中的查找结果
return new OdpIpWhiteListService().CheckIpExists(ip);
}
/// <summary>
/// 获取当前应用程序指定CacheKey的Cache值
/// </summary>
/// <param name="CacheKey"></param>
/// <returns></returns>
public static object GetCache(string CacheKey)
{
System.Web.Caching.Cache objCache = HttpRuntime.Cache;
return objCache[CacheKey];
}
/// <summary>
/// 设置缓存
/// </summary>
/// <param name="CacheKey"></param>
/// <param name="objObject"></param>
/// <param name="expires_in"></param>
public static void SetCache(string CacheKey, object objObject, double expires_in)
{
Cache objCache = HttpRuntime.Cache;
objCache.Insert(CacheKey, objObject, null, DateTime.Now.AddHours(expires_in), Cache.NoSlidingExpiration);
}
/// <summary>
/// 获取IP地址
/// </summary>
/// <returns></returns>
public static string GetIpAddress()
{
string result = HttpContext.Current.Request.ServerVariables["HTTP_CDN_SRC_IP"]; // 判断CDN IP是否存在,如果存在获取真实ip
if (string.IsNullOrEmpty(result))
result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; // 获取发起请求的远程主机 ip
if (string.IsNullOrEmpty(result))
result = HttpContext.Current.Request.UserHostAddress;
if (string.IsNullOrEmpty(result) || !IsIP(result))
return "127.0.0.1";
return result;
}
public static bool IsIP(string ip)
{
return Regex.IsMatch(ip, "^((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)$");
}
}
接口上增加标记即可
