添加项目文件。

This commit is contained in:
JianWeie
2021-12-20 21:27:32 +08:00
parent 747486f5cb
commit 82d825b7a5
3514 changed files with 887941 additions and 0 deletions

View File

@@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\CoreCms.Net.Auth\CoreCms.Net.Auth.csproj" />
<ProjectReference Include="..\CoreCms.Net.Configuration\CoreCms.Net.Configuration.csproj" />
<ProjectReference Include="..\CoreCms.Net.Core\CoreCms.Net.Core.csproj" />
<ProjectReference Include="..\CoreCms.Net.IServices\CoreCms.Net.IServices.csproj" />
<ProjectReference Include="..\CoreCms.Net.Loging\CoreCms.Net.Loging.csproj" />
<ProjectReference Include="..\CoreCms.Net.Utility\CoreCms.Net.Utility.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,72 @@
/***********************************************************************
* Project: CoreCms.Net *
* Web: https://CoreCms.Net *
* ProjectName: 核心内容管理系统 *
* Author: 大灰灰 *
* Email: JianWeie@163.com *
* Versions: 1.0 *
* CreateTime: 2020-02-05 19:08:19
* NameSpace: CoreCms.Net.Framework.Middlewares
* FileName: ExceptionHandlerMidd
* ClassDescription:
***********************************************************************/
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using CoreCms.Net.Loging;
using CoreCms.Net.Model.ViewModels.UI;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace CoreCms.Net.Middlewares
{
/// <summary>
/// 异常错误统一返回记录
/// </summary>
public class ExceptionHandlerMiddForAdmin
{
private readonly RequestDelegate _next;
public ExceptionHandlerMiddForAdmin(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private async Task HandleExceptionAsync(HttpContext context, Exception ex)
{
if (ex == null) return;
NLogUtil.WriteAll(NLog.LogLevel.Error, LogType.Web, "全局捕获异常", "全局捕获异常", new Exception("全局捕获异常", ex));
await WriteExceptionAsync(context, ex).ConfigureAwait(false);
}
private static async Task WriteExceptionAsync(HttpContext context, Exception e)
{
if (e is UnauthorizedAccessException) context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
else if (e is Exception) context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
context.Response.ContentType = "application/json";
var jm = new AdminUiCallBack();
jm.code = 500;
jm.data = e;
jm.msg = "全局捕获异常";
await context.Response.WriteAsync(JsonConvert.SerializeObject(jm)).ConfigureAwait(false);
}
}
}

View File

@@ -0,0 +1,81 @@
/***********************************************************************
* Project: CoreCms.Net *
* Web: https://CoreCms.Net *
* ProjectName: 核心内容管理系统 *
* Author: 大灰灰 *
* Email: JianWeie@163.com *
* Versions: 1.0 *
* CreateTime: 2020-02-05 19:08:19
* NameSpace: CoreCms.Net.Framework.Middlewares
* FileName: ExceptionHandlerMidd
* ClassDescription:
***********************************************************************/
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using CoreCms.Net.IServices;
using CoreCms.Net.Loging;
using CoreCms.Net.Model.Entities;
using CoreCms.Net.Model.ViewModels.UI;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
using Newtonsoft.Json;
namespace CoreCms.Net.Middlewares
{
/// <summary>
/// 异常错误统一返回记录
/// </summary>
public class ExceptionHandlerMiddForClent
{
private readonly RequestDelegate _next;
public ExceptionHandlerMiddForClent(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private async Task HandleExceptionAsync(HttpContext context, Exception ex)
{
if (ex == null) return;
NLogUtil.WriteAll(NLog.LogLevel.Error, LogType.ApiRequest, "全局捕获异常", "全局捕获异常", new Exception("全局捕获异常", ex));
await WriteExceptionAsync(context, ex).ConfigureAwait(false);
}
private static async Task WriteExceptionAsync(HttpContext context, Exception e)
{
if (e is UnauthorizedAccessException)
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
else if (e is Exception)
context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
context.Response.ContentType = "application/json";
var jm = new WebApiCallBack();
jm.status = false;
jm.code = 500;
jm.data = e;
jm.msg = "全局数据异常";
await context.Response.WriteAsync(JsonConvert.SerializeObject(jm)).ConfigureAwait(false);
}
}
}

View File

@@ -0,0 +1,107 @@
/***********************************************************************
* Project: CoreCms.Net *
* Web: https://CoreCms.Net *
* ProjectName: 核心内容管理系统 *
* Author: 大灰灰 *
* Email: JianWeie@163.com *
* Versions: 1.0 *
* CreateTime: 2020-02-03 23:33:49
* NameSpace: CoreCms.Net.Framework.Middlewares
* FileName: IPLogMildd
* ClassDescription:
***********************************************************************/
using System;
using System.Threading.Tasks;
using CoreCms.Net.Configuration;
using CoreCms.Net.Loging;
using CoreCms.Net.Model.ViewModels.LogInfo;
using CoreCms.Net.Utility.Extensions;
using CoreCms.Net.Utility.Helper;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
namespace CoreCms.Net.Middlewares
{
/// <summary>
/// 中间件
/// 记录IP请求数据
/// </summary>
public class IPLogMildd
{
/// <summary>
///
/// </summary>
private readonly RequestDelegate _next;
/// <summary>
///
/// </summary>
/// <param name="next"></param>
public IPLogMildd(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
if (AppSettingsConstVars.MiddlewareIpLogEnabled)
{
// 过滤,只有接口
if (context.Request.Path.Value != null && (context.Request.Path.Value.Contains("api") || context.Request.Path.Value.Contains("Api")))
{
context.Request.EnableBuffering();
try
{
// 存储请求数据
var dt = DateTime.Now;
var request = context.Request;
var requestInfo = JsonConvert.SerializeObject(new RequestInfo()
{
Ip = GetClientIp(context),
Url = request.Path.ObjectToString().TrimEnd('/').ToLower(),
Datetime = dt.ToString("yyyy-MM-dd HH:mm:ss"),
Date = dt.ToString("yyyy-MM-dd"),
Week = CommonHelper.GetWeek(),
});
if (!string.IsNullOrEmpty(requestInfo))
{
Parallel.For(0, 1, e =>
{
LogLockHelper.OutSql2Log("RequestIpInfoLog", "RequestIpInfoLog" + dt.ToString("yyyy-MM-dd-HH"), new string[] { requestInfo + "," }, false);
});
request.Body.Position = 0;
}
await _next(context);
}
catch (Exception)
{
}
}
else
{
await _next(context);
}
}
else
{
await _next(context);
}
}
public static string GetClientIp(HttpContext context)
{
var ip = context.Request.Headers["X-Forwarded-For"].ObjectToString();
if (string.IsNullOrEmpty(ip))
{
if (context.Connection.RemoteIpAddress != null)
{
ip = context.Connection.RemoteIpAddress.MapToIPv4().ObjectToString();
}
}
return ip;
}
}
}

View File

@@ -0,0 +1,88 @@
/***********************************************************************
* Project: CoreCms.Net *
* Web: https://CoreCms.Net *
* ProjectName: 核心内容管理系统 *
* Author: 大灰灰 *
* Email: JianWeie@163.com *
* Versions: 1.0 *
* CreateTime: 2020-02-03 23:29:27
* FileName: MiddlewareHelpers
* ClassDescription:
***********************************************************************/
using CoreCms.Net.Core;
using Microsoft.AspNetCore.Builder;
namespace CoreCms.Net.Middlewares
{
/// <summary>
/// 中间件
/// </summary>
public static class MiddlewareHelpers
{
/// <summary>
/// 请求响应中间件
/// </summary>
/// <param name="app"></param>
/// <returns></returns>
public static IApplicationBuilder UseRequestResponseLog(this IApplicationBuilder app)
{
return app.UseMiddleware<RequRespLogMildd>();
}
/// <summary>
/// 异常处理中间件(后端模式)
/// </summary>
/// <param name="app"></param>
/// <returns></returns>
public static IApplicationBuilder UseExceptionHandlerMiddForAdmin(this IApplicationBuilder app)
{
return app.UseMiddleware<ExceptionHandlerMiddForAdmin>();
}
/// <summary>
/// 异常处理中间件(客户端)
/// </summary>
/// <param name="app"></param>
/// <returns></returns>
public static IApplicationBuilder UseExceptionHandlerMiddForClent(this IApplicationBuilder app)
{
return app.UseMiddleware<ExceptionHandlerMiddForClent>();
}
/// <summary>
/// SignalR中间件
/// </summary>
/// <param name="app"></param>
/// <returns></returns>
public static IApplicationBuilder UseSignalRSendMildd(this IApplicationBuilder app)
{
return app.UseMiddleware<SignalRSendMildd>();
}
/// <summary>
/// IP请求中间件
/// </summary>
/// <param name="app"></param>
/// <returns></returns>
public static IApplicationBuilder UseIpLogMildd(this IApplicationBuilder app)
{
return app.UseMiddleware<IPLogMildd>();
}
/// <summary>
/// 用户访问接口日志中间件
/// </summary>
/// <param name="app"></param>
/// <returns></returns>
public static IApplicationBuilder UseRecordAccessLogsMildd(this IApplicationBuilder app)
{
return app.UseMiddleware<RecordAccessLogsMildd>();
}
}
}

View File

@@ -0,0 +1,162 @@

using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using CoreCms.Net.Auth.HttpContextUser;
using CoreCms.Net.Configuration;
using CoreCms.Net.Loging;
using CoreCms.Net.Utility.Extensions;
namespace CoreCms.Net.Middlewares
{
/// <summary>
/// 中间件
/// 记录用户方访问数据
/// </summary>
public class RecordAccessLogsMildd
{
/// <summary>
///
/// </summary>
private readonly RequestDelegate _next;
private readonly IHttpContextUser _user;
private readonly ILogger<RecordAccessLogsMildd> _logger;
private readonly Stopwatch _stopwatch;
/// <summary>
/// 构造
/// </summary>
/// <param name="next"></param>
/// <param name="user"></param>
/// <param name="logger"></param>
public RecordAccessLogsMildd(RequestDelegate next, IHttpContextUser user, ILogger<RecordAccessLogsMildd> logger)
{
_next = next;
_user = user;
_logger = logger;
_stopwatch = new Stopwatch();
}
public async Task InvokeAsync(HttpContext context)
{
if (AppSettingsConstVars.MiddlewareRecordAccessLogsEnabled)
{
var api = context.Request.Path.ObjectToString().TrimEnd('/').ToLower();
var ignoreApis = AppSettingsConstVars.MiddlewareRecordAccessLogsIgnoreApis;
// 过滤,只有接口
if (api.Contains("api") && !ignoreApis.Contains(api))
{
_stopwatch.Restart();
var userAccessModel = new UserAccessModel();
HttpRequest request = context.Request;
userAccessModel.API = api;
userAccessModel.User = _user.Name;
userAccessModel.IP = IPLogMildd.GetClientIp(context);
userAccessModel.BeginTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
userAccessModel.RequestMethod = request.Method;
userAccessModel.Agent = request.Headers["User-Agent"].ObjectToString();
// 获取请求body内容
if (request.Method.ToLower().Equals("post") || request.Method.ToLower().Equals("put"))
{
// 启用倒带功能,就可以让 Request.Body 可以再次读取
request.EnableBuffering();
Stream stream = request.Body;
byte[] buffer = new byte[request.ContentLength.Value];
stream.Read(buffer, 0, buffer.Length);
userAccessModel.RequestData = Encoding.UTF8.GetString(buffer);
request.Body.Position = 0;
}
else if (request.Method.ToLower().Equals("get") || request.Method.ToLower().Equals("delete"))
{
userAccessModel.RequestData = HttpUtility.UrlDecode(request.QueryString.ObjectToString(), Encoding.UTF8);
}
// 获取Response.Body内容
var originalBodyStream = context.Response.Body;
using (var responseBody = new MemoryStream())
{
context.Response.Body = responseBody;
await _next(context);
var responseBodyData = await GetResponse(context.Response);
await responseBody.CopyToAsync(originalBodyStream);
}
var dt = DateTime.Now;
// 响应完成记录时间和存入日志
context.Response.OnCompleted(() =>
{
_stopwatch.Stop();
userAccessModel.OPTime = _stopwatch.ElapsedMilliseconds + "ms";
// 自定义log输出
var requestInfo = JsonConvert.SerializeObject(userAccessModel);
Parallel.For(0, 1, e =>
{
LogLockHelper.OutSql2Log("RecordAccessLogs", "RecordAccessLogs" + dt.ToString("yyyy-MM-dd-HH"), new string[] { requestInfo + "," }, false);
});
return Task.CompletedTask;
});
}
else
{
await _next(context);
}
}
else
{
await _next(context);
}
}
/// <summary>
/// 获取响应内容
/// </summary>
/// <param name="response"></param>
/// <returns></returns>
public async Task<string> GetResponse(HttpResponse response)
{
response.Body.Seek(0, SeekOrigin.Begin);
var text = await new StreamReader(response.Body).ReadToEndAsync();
response.Body.Seek(0, SeekOrigin.Begin);
return text;
}
}
public class UserAccessModel
{
public string User { get; set; }
public string IP { get; set; }
public string API { get; set; }
public string BeginTime { get; set; }
public string OPTime { get; set; }
public string RequestMethod { get; set; }
public string RequestData { get; set; }
public string Agent { get; set; }
}
}

View File

@@ -0,0 +1,129 @@
/***********************************************************************
* Project: CoreCms.Net *
* Web: https://CoreCms.Net *
* ProjectName: 核心内容管理系统 *
* Author: 大灰灰 *
* Email: JianWeie@163.com *
* Versions: 1.0 *
* CreateTime: 2020-02-03 23:30:52
* FileName: RequRespLogMildd
* ClassDescription:
***********************************************************************/
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using CoreCms.Net.Configuration;
using CoreCms.Net.Loging;
using CoreCms.Net.Utility.Extensions;
using Microsoft.AspNetCore.Http;
namespace CoreCms.Net.Middlewares
{
/// <summary>
/// 中间件
/// 记录请求和响应数据
/// </summary>
public class RequRespLogMildd
{
/// <summary>
///
/// </summary>
private readonly RequestDelegate _next;
/// <summary>
///
/// </summary>
/// <param name="next"></param>
public RequRespLogMildd(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
if (AppSettingsConstVars.MiddlewareRequestResponseLogEnabled)
{
// 过滤,只有接口
if (context.Request.Path.Value.Contains("api") || context.Request.Path.Value.Contains("Api"))
{
context.Request.EnableBuffering();
Stream originalBody = context.Response.Body;
try
{
// 存储请求数据
await RequestDataLog(context);
using (var ms = new MemoryStream())
{
context.Response.Body = ms;
await _next(context);
// 存储响应数据
ResponseDataLog(context.Response, ms);
ms.Position = 0;
await ms.CopyToAsync(originalBody);
}
}
catch (Exception)
{
// 记录异常
//ErrorLogData(context.Response, ex);
}
finally
{
context.Response.Body = originalBody;
}
}
else
{
await _next(context);
}
}
else
{
await _next(context);
}
}
private async Task RequestDataLog(HttpContext context)
{
var request = context.Request;
var sr = new StreamReader(request.Body);
var content = $" QueryData:{request.Path + request.QueryString}\r\n BodyData:{await sr.ReadToEndAsync()}";
if (!string.IsNullOrEmpty(content))
{
Parallel.For(0, 1, e =>
{
LogLockHelper.OutSql2Log("RequestResponseLog", "RequestResponseLog" + DateTime.Now.ToString("yyyy-MM-dd-HH"), new string[] { "Request Data:", content });
});
request.Body.Position = 0;
}
}
private void ResponseDataLog(HttpResponse response, MemoryStream ms)
{
ms.Position = 0;
var ResponseBody = new StreamReader(ms).ReadToEnd();
// 去除 Html
var reg = "<[^>]+>";
var isHtml = Regex.IsMatch(ResponseBody, reg);
if (!string.IsNullOrEmpty(ResponseBody))
{
Parallel.For(0, 1, e =>
{
LogLockHelper.OutSql2Log("RequestResponseLog", "RequestResponseLog" + DateTime.Now.ToString("yyyy-MM-dd-HH"), new string[] { "Response Data:", ResponseBody });
});
}
}
}
}

View File

@@ -0,0 +1,57 @@
/***********************************************************************
* Project: CoreCms.Net *
* Web: https://CoreCms.Net *
* ProjectName: 核心内容管理系统 *
* Author: 大灰灰 *
* Email: JianWeie@163.com *
* CreateTime: 2020-09-06 23:37:04
* Description: 暂无
***********************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using CoreCms.Net.Utility.Hub;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.SignalR;
namespace CoreCms.Net.Middlewares
{
/// <summary>
/// 中间件
/// SignalR发送数据
/// </summary>
public class SignalRSendMildd
{
/// <summary>
///
/// </summary>
private readonly RequestDelegate _next;
private readonly IHubContext<ChatHub> _hubContext;
/// <summary>
///
/// </summary>
/// <param name="next"></param>
/// <param name="hubContext"></param>
public SignalRSendMildd(RequestDelegate next, IHubContext<ChatHub> hubContext)
{
_next = next;
_hubContext = hubContext;
}
public async Task InvokeAsync(HttpContext context)
{
await _next(context);
}
}
}