using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Serein.Library.Api.Api;
using Serein.Library.Core.IOC;
using Serein.Tool;
using System.Collections;
using System.Collections.Concurrent;
using System.Net;
using System.Reflection;
using System.Text;
using System.Web;
using Enum = System.Enum;
using Type = System.Type;
namespace Serein.Library.Core.Http
{
/*
Router类负责解析请求的url,url参数,boby参数
根据url
web server 监听类,监听外部的请求
router 选择对应的控制器
agent 负责传入对应的参数,注入依赖
*/
///
/// 路由注册与解析
///
public class Router
{
private readonly ConcurrentDictionary _controllerAutoHosting; // 存储是否实例化
private readonly ConcurrentDictionary _controllerTypes; // 存储控制器类型
private readonly ConcurrentDictionary _controllerInstances; // 存储控制器实例对象
private readonly ConcurrentDictionary> _routes; // 用于存储路由信息
private readonly ISereinIoc serviceRegistry; // 用于存储路由信息
//private Type PostRequest;
public Router(ISereinIoc serviceRegistry) // 构造函数,初始化 Router 类的新实例
{
this.serviceRegistry = serviceRegistry;
_routes = new ConcurrentDictionary>(); // 初始化路由字典
_controllerAutoHosting = new ConcurrentDictionary(); // 初始化控制器实例对象字典
_controllerTypes = new ConcurrentDictionary(); // 初始化控制器实例对象字典
_controllerInstances = new ConcurrentDictionary(); // 初始化控制器实例对象字典
foreach (API method in Enum.GetValues(typeof(API))) // 遍历 HTTP 枚举类型的所有值
{
_routes.TryAdd(method.ToString(), new ConcurrentDictionary()); // 初始化每种 HTTP 方法对应的路由字典
}
// 获取当前程序集
Assembly assembly = Assembly.GetExecutingAssembly();
// 获取包含“Controller”名称的类型
var controllerTypes = assembly.GetTypes()
.Where(t => t.Name.Contains("Controller"));
Type baseAttribute = typeof(AutoHostingAttribute);
Type baseController = typeof(ControllerBase);
foreach (var controllerType in controllerTypes)
{
if (controllerType.IsSubclassOf(baseController) && controllerType.IsDefined(baseAttribute))
{
// 如果属于控制器,并标记了AutoHosting特性,进行自动注册
AutoRegisterAutoController(controllerType);
}
else
{
continue;
}
}
}
///
/// 自动注册 自动实例化控制器 类型
///
///
public void AutoRegisterAutoController(Type controllerType) // 方法声明,用于注册并实例化控制器类型
{
if (!controllerType.IsClass || controllerType.IsAbstract) return; // 如果不是类或者是抽象类,则直接返回
var autoHostingAttribute = controllerType.GetCustomAttribute();
if (autoHostingAttribute != null) {
foreach (var method in controllerType.GetMethods()) // 遍历控制器类型的所有方法
{
var apiGetAttribute = method.GetCustomAttribute();
var apiPostAttribute = method.GetCustomAttribute();
if( apiGetAttribute == null && apiPostAttribute == null )
{
continue;
}
WebApiAttribute webApiAttribute = new WebApiAttribute()
{
Type = apiGetAttribute != null ? API.GET : API.POST,
Url = apiGetAttribute != null ? apiGetAttribute.Url : apiPostAttribute.Url,
IsUrl = apiGetAttribute != null ? apiGetAttribute.IsUrl : apiPostAttribute.IsUrl,
};
if (apiPostAttribute != null) // 如果存在 WebAPIAttribute 属性
{
var url = AddRoutesUrl(autoHostingAttribute,
webApiAttribute,
controllerType, method);
Console.WriteLine(url);
if (url == null) continue;
_controllerAutoHosting[url] = true;
_controllerTypes[url] = controllerType;
_controllerInstances[url] = null;
}
/* var routeAttribute = method.GetCustomAttribute(); // 获取方法上的 WebAPIAttribute 自定义属性
if (routeAttribute != null) // 如果存在 WebAPIAttribute 属性
{
var url = AddRoutesUrl(autoHostingAttribute, routeAttribute, controllerType, method);
Console.WriteLine(url);
if (url == null) continue;
_controllerAutoHosting[url] = true;
_controllerTypes[url] = controllerType;
_controllerInstances[url] = null;
}*/
}
}
}
///
/// 手动注册 自动实例化控制器实例
///
public void RegisterAutoController() // 方法声明,用于动态注册路由
{
Type controllerType = typeof(T); // 获取控制器实例的类型
foreach (var method in controllerType.GetMethods()) // 遍历控制器类型的所有方法
{
var apiGetAttribute = method.GetCustomAttribute();
var apiPostAttribute = method.GetCustomAttribute();
if (apiGetAttribute == null && apiPostAttribute == null)
{
continue;
}
WebApiAttribute webApiAttribute = new WebApiAttribute()
{
Type = apiGetAttribute != null ? API.GET : API.POST,
Url = apiGetAttribute != null ? apiGetAttribute.Url : apiPostAttribute.Url,
IsUrl = apiGetAttribute != null ? apiGetAttribute.IsUrl : apiPostAttribute.IsUrl,
};
var url = AddRoutesUrl(null, webApiAttribute, controllerType, method);
if (url == null) continue;
_controllerAutoHosting[url] = true;
_controllerTypes[url] = controllerType;
_controllerInstances[url] = null;
}
}
///
/// 手动注册 实例持久控制器实例
///
///
public void RegisterController(TController controllerInstance) where TController : ControllerBase // 方法声明,用于动态注册路由
{
if(controllerInstance == null) return;
Type controllerType = controllerInstance.GetType(); // 获取控制器实例的类型
foreach (var method in controllerType.GetMethods()) // 遍历控制器类型的所有方法
{
var apiGetAttribute = method.GetCustomAttribute();
var apiPostAttribute = method.GetCustomAttribute();
if (apiGetAttribute == null && apiPostAttribute == null)
{
continue;
}
WebApiAttribute webApiAttribute = new WebApiAttribute()
{
Type = apiGetAttribute != null ? API.GET : API.POST,
Url = apiGetAttribute != null ? apiGetAttribute.Url : apiPostAttribute.Url,
IsUrl = apiGetAttribute != null ? apiGetAttribute.IsUrl : apiPostAttribute.IsUrl,
};
var url = AddRoutesUrl(null, webApiAttribute, controllerType, method);
if (url == null) continue;
_controllerInstances[url] = controllerInstance;
_controllerAutoHosting[url] = false;
}
}
///
/// 从方法中收集路由信息
///
///
public string AddRoutesUrl(AutoHostingAttribute autoHostingAttribute, WebApiAttribute webAttribute, Type controllerType, MethodInfo method)
{
string controllerName;
if (autoHostingAttribute == null || string.IsNullOrWhiteSpace(autoHostingAttribute.Url))
{
controllerName = controllerType.Name.Replace("Controller", "").ToLower(); // 获取控制器名称并转换为小写
}
else
{
controllerName = autoHostingAttribute.Url;
}
var httpMethod = webAttribute.Type; // 获取 HTTP 方法
var customUrl = webAttribute.Url; // 获取自定义 URL
string url;
if (webAttribute.IsUrl)
{
if (string.IsNullOrEmpty(customUrl)) // 如果自定义 URL 为空
{
url = $"/{controllerName}/{method.Name}".ToLower(); // 构建默认 URL
}
else
{
customUrl = CleanUrl(customUrl);
url = $"/{controllerName}/{method.Name}/{customUrl}".ToLower();// 清理自定义 URL,并构建新的 URL
}
_routes[httpMethod.ToString()].TryAdd(url, method); // 将 URL 和方法添加到对应的路由字典中
}
else
{
if (string.IsNullOrEmpty(customUrl)) // 如果自定义 URL 为空
{
url = $"/{controllerName}".ToLower(); // 构建默认 URL
}
else
{
customUrl = CleanUrl(customUrl);
url = $"/{controllerName}/{customUrl}".ToLower();// 清理自定义 URL,并构建新的 URL
}
_routes[httpMethod.ToString()].TryAdd(url, method); // 将 URL 和方法添加到对应的路由字典中
}
return url;
}
///
/// 收集路由信息
///
///
public void CollectRoutes(Type controllerType)
{
string controllerName = controllerType.Name.Replace("Controller", "").ToLower(); // 获取控制器名称并转换为小写
foreach (var method in controllerType.GetMethods()) // 遍历控制器类型的所有方法
{
var routeAttribute = method.GetCustomAttribute(); // 获取方法上的 WebAPIAttribute 自定义属性
if (routeAttribute != null) // 如果存在 WebAPIAttribute 属性
{
var customUrl = routeAttribute.Url; // 获取自定义 URL
string url;
if (string.IsNullOrEmpty(customUrl)) // 如果自定义 URL 为空
{
url = $"/api/{controllerName}/{method.Name}".ToLower(); // 构建默认 URL
}
else
{
customUrl = CleanUrl(customUrl);
url = $"/api/{controllerName}/{method.Name}/{customUrl}".ToLower();// 清理自定义 URL,并构建新的 URL
}
var httpMethod = routeAttribute.Type; // 获取 HTTP 方法
_routes[httpMethod.ToString()].TryAdd(url, method); // 将 URL 和方法添加到对应的路由字典中
}
}
}
///
/// 解析路由,调用对应的方法
///
///
///
public async Task RouteAsync(HttpListenerContext context)
{
var request = context.Request; // 获取请求对象
var response = context.Response; // 获取响应对象
var url = request.Url; // 获取请求的 URL
var httpMethod = request.HttpMethod; // 获取请求的 HTTP 方法
var template = request.Url.AbsolutePath.ToLower();
if (!_routes[httpMethod].TryGetValue(template, out MethodInfo method))
{
return false;
}
var routeValues = GetUrlData(url); // 解析 URL 获取路由参数
ControllerBase controllerInstance;
if (!_controllerAutoHosting[template])
{
controllerInstance = (ControllerBase)_controllerInstances[template];
}
else
{
controllerInstance = (ControllerBase)serviceRegistry.Instantiate(_controllerTypes[template]);// 使用反射创建控制器实例
}
if (controllerInstance == null)
{
return false; // 未找到控制器实例
}
controllerInstance.Url = url.AbsolutePath;
object result;
switch (httpMethod) // 根据请求的 HTTP 方法执行不同的操作
{
case "GET": // 如果是 GET 请求,传入方法、控制器、url参数
result = InvokeControllerMethodWithRouteValues(method, controllerInstance, routeValues);
break;
case "POST": // POST 请求传入方法、控制器、请求体内容,url参数
var requestBody = await ReadRequestBodyAsync(request); // 读取请求体内容
controllerInstance.BobyData = requestBody;
var requestJObject = requestBody.FromJSON