加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用Attribute创建Request IP约束

发布时间:2020-12-16 01:30:53 所属栏目:百科 来源:网络整理
导读:我想做以下(伪代码): [InternalOnly]public ActionResult InternalMethod(){ //magic } “InternalOnly”属性适用于在执行任何其他操作之前应检查HttpContext请求IP是否已知值的方法. 我将如何创建这个“InternalOnly”属性? 解决方法 您可以创建自定义过
我想做以下(伪代码):

[InternalOnly]
public ActionResult InternalMethod()
{ //magic }

“InternalOnly”属性适用于在执行任何其他操作之前应检查HttpContext请求IP是否已知值的方法.

我将如何创建这个“InternalOnly”属性?

解决方法

您可以创建自定义过滤器属性:

public class InternalOnly : FilterAttribute
{
    public void OnAuthorization (AuthorizationContext filterContext)
    {
        if (!IsIntranet (filterContext.HttpContext.Request.UserHostAddress))
        {
            throw new HttpException ((int)HttpStatusCode.Forbidden,"Access forbidden.");
        }
    }

    private bool IsIntranet (string userIP)
    {
        // match an internal IP (ex: 127.0.0.1)
        return !string.IsNullOrEmpty (userIP) && Regex.IsMatch (userIP,"^127");
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读