MVC BaseController 基本許可權控制
阿新 • • 發佈:2019-01-26
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() {
}
/// <summary>
/// 讀取controller及action方便做許可權判斷
/// </summary>
/// <param name="filterContext"></param>
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);
}
/// <summary>
/// 初始化
/// </summary>
/// <param name="requestContext"></param>
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
}
/// <summary>
/// 捕捉500錯誤 404需要配置
/// </summary>
/// <param name="filterContext"></param>
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;
}
}
}