代码改变世界

[转]asp.net mvc 获取IP方法的扩展

2010-03-08 00:29  AnyKoro  阅读(630)  评论(1编辑  收藏  举报

1.扩展方法必须在非泛型静态类中定义

2.扩展方法必须是静态的

3.不能在静态类中声明实例成员

public static class PubMethod
    {
        public static string GetIP(this Controller ctrl)
        {
            string ip;
            if (ctrl.HttpContext.Request.ServerVariables["HTTP_VIA"] != null)             {
                ip = ctrl.HttpContext.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();             }
            else            {
                ip = ctrl.HttpContext.Request.ServerVariables["REMOTE_ADDR"].ToString();             }
            return ip;

        }
    }

这样就可以在Action里面直接调用了 PubMethod.GetIP(this);