MVC BaseController 基本权限控制

C# mvc 基于Action的权限控制,大概代码如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

public class BaseController : Controller
{

    protected BaseController() { 

    }
    /// 
    /// 读取controller及action方便做权限判断
    /// 
    /// 
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        //controller
        var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
        //action
        var actionName = filterContext.ActionDescriptor.ActionName;
        //获取参数数组
        var arrParameter = filterContext.ActionDescriptor.GetParameters();

        //根据索引获取对应参数名 
        //如果可以确定参数名称可以直接用ActionParameters通过Key来获取,Key指参数名称
        #region
        if (controllerName == "RestFul")
        {
            var keys = filterContext.ActionParameters["keys"];
            if (keys == null)
            {
                filterContext.Result = IsNoAuthority();
            }
        }
        #endregion
        base.OnActionExecuting(filterContext);         
    }
    /// 
    /// 初始化
    /// 
    /// 
    protected override void Initialize(RequestContext requestContext)
    {
        base.Initialize(requestContext); 
    }
    /// 
    /// 捕捉500错误 404需要配置
    /// 
    /// 
    protected override void OnException(ExceptionContext filterContext)
    {
        // 错误日志编写    
        string controllerNamer = filterContext.RouteData.Values["controller"].ToString();
        string actionName = filterContext.RouteData.Values["action"].ToString();
        string exception = filterContext.Exception.ToString();
        // 执行基类中的OnException    
        base.OnException(filterContext);  
    }
    public JsonResult IsNoAuthority()
    {
        JsonStatus status = new JsonStatus("-1", "无权访问接口,请授权");
        var json = new JsonResult();
        json.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
        json.Data = status;
        return json;
    }
    public class JsonStatus
    {
        public string code { set; get; }
        public string error { set; get; }
        public JsonStatus()
        {

        }
        public JsonStatus(string _code, string _error)
        {
            this.code = _code;
            this.error = _error;
        }
    }
}

你可能感兴趣的:(C#)