using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Newtonsoft.Json; using System.Text.RegularExpressions; using System.Threading.Tasks; using VirtualCoin.MvcWeb.Models; namespace VirtualCoin.MvcWeb.Commmon { public static class RequestValidationExtensions { public static IApplicationBuilder UseRequestValidation( this IApplicationBuilder builder) { return builder.UseMiddleware<RequestValidation>(); } } public class RequestValidation { private readonly RequestDelegate _next; public RequestValidation(RequestDelegate next) { _next = next; } public async Task InvokeAsync(HttpContext context) { const string regRole = @"<[^>]*>"; Regex rx = new Regex(regRole, RegexOptions.Compiled | RegexOptions.IgnoreCase); if (context.Request.Method == "POST") { try { var form = await context.Request.ReadFormAsync(); foreach (var item in form.Keys) { if (rx.Matches(form[item]).Count > 0) { await sendErorMsgAsync(context); return; } } } catch { } foreach (var item in context.Request.Query.Keys) { if (rx.Matches(context.Request.Query[item]).Count > 0) { await sendErorMsgAsync(context); return; } } } else if (context.Request.Method == "GET") { foreach (var item in context.Request.Query.Keys) { if (rx.Matches(context.Request.Query[item]).Count > 0) { await sendErorMsgAsync(context); return; } } } await _next(context); } private async Task sendErorMsgAsync(HttpContext context) { if (context.Request.Headers["X-Requested-With"] == "XMLHttpRequest") { context.Response.StatusCode = 200;//laytable等组件没有暴露500回调接口,为了兼容性所以ajax暂时只可以走200 context.Response.ContentType = "application/Json"; await context.Response.WriteAsync(JsonConvert.SerializeObject(ResultMessage.Error("提交的数据包含非法字符"))); } else { //context.Response.StatusCode = 500; //context.Response.ContentType = "text/plan;charset=utf8;"; //await context.Response.WriteAsync("提交的数据包含非法字符"); var jsCode = string.Format("alert('提交的数据包含非法字符'); window.history.go(-1);"); await context.Response.WriteAsync(JavaScriptContent(jsCode)); } } private string JavaScriptContent(string JsCode) { var Tag = @"<!doctype html> <html> <head> <meta charset=""utf-8"" /> <title>...</title> </head> <body> <script type=""text/javascript"">{0}</script> </body> </html>"; if (string.IsNullOrEmpty(JsCode)) { JsCode = ""; } return string.Format(Tag, JsCode); } } }
在 startup中注册:
app.UseRequestValidation();