BaseController.cs
3.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
using Hh.Mes.Common;
using Hh.Mes.Common.Json;
using Hh.Mes.Common.log;
using Hh.Mes.POJO.Response;
using Hh.Mes.Service.SystemAuth;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Linq;
using System.Reflection;
namespace WebMvc
{
/// <summary>
/// 基础控制器
/// <para>用于控制登录用户是否有权限访问指定的Action</para>
/// </summary>
public class BaseController : SSOController
{
public Response Result = new Response();
protected string controllerName; //当前控制器小写名称
protected string actionName; //当前Action小写名称
/// <summary>
/// 上下文
/// </summary>
public HttpContext context;
public BaseController(IAuth authUtil) : base(authUtil)
{
}
/// <summary>
/// https://blog.csdn.net/mango_love/article/details/84992020
/// </summary>
/// <param name="filterContext"></param>
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
ActionBefore(filterContext);
actionName = filterContext.RouteData.Values["action"].ToString();
var function = ((TypeInfo)GetType()).DeclaredMethods.FirstOrDefault(u => u.Name.Equals(actionName, StringComparison.OrdinalIgnoreCase));
if (function == null)
{
Log4NetHelper.Instance.Info("请检查模块设置URL设置是否正确、请注意大小写! " + actionName);
throw new ArgumentNullException($"请检查模块设置URL设置是否正确、请注意大小写!" + actionName);
}
//权限验证标识
var authorize = function.GetCustomAttribute(typeof(AuthenticateAttribute));
if (authorize == null) return;
controllerName = filterContext.RouteData.Values["controller"].ToString();
var currentModule = authStrategyContext?.Modules.FirstOrDefault(u => u.Url.Contains(controllerName));
//当前登录用户没有Action记录&&Action有authenticate标识
if (currentModule == null)
{
Log4NetHelper.Instance.Info("登入失效:BaseController【currentModule】为空 ");
filterContext.Result = new RedirectResult("/Login/Index");
return;
}
}
/// <summary>
/// 获取所有标记为 SysPublicEnum特性的枚举,转换为JSON 格式字符串, 存储在 ViewData 中以供视图使用。
/// </summary>
/// <remarks>
/// 此方法会加载 Hh.Mes.POJO 程序集中的所有枚举类型,
/// 并通过反射查找被标记的枚举。将每个枚举转换为 JSON 字符串后,以枚举名称作为键存储在 ViewData 中。
/// </remarks>
public void ResponseEnumJosn()
{
// 加载特定的 DLL
var assembly = Assembly.Load("Hh.Mes.POJO");
var enumTypes = assembly.GetTypes()
.Where(t => t.IsEnum && t.GetCustomAttributes(typeof(SysPublicEnumAttribute), false).Any())
.ToList();
foreach (var enumType in enumTypes)
{
string jsonEnum = enumType.GetJsonEnum(enumType.Name);
ViewData[enumType.Name] = jsonEnum;
}
ViewData["EnumTypes"] = enumTypes;
}
public string Serialize(dynamic response)
{
return JsonHelper.Instance.Serialize(response);
}
}
}