添加项目文件。

This commit is contained in:
zgf committed 2023-07-25 19:20:18 +08:00
1 parent 05e131ca4e
commit 514d6f5255
1162 files changed
+81255

No files matched your search

@@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Extensions.Localization;
using WalkingTec.Mvvm.Core;
namespace WalkingTec.Mvvm.Mvc
{
public static class ActionDescriptionExtension
{
public static string GetDescription(this ActionDescriptionAttribute self, IBaseController controller)
{
return self.GetDescription(controller.GetType());
}
public static string GetDescription(this ActionDescriptionAttribute self, Type controllertype)
{
string rv = "";
if (string.IsNullOrEmpty(self.Description) == false)
{
rv = Core.CoreProgram._localizer?[self.Description];
}
return rv;
}
}
}
@@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using WalkingTec.Mvvm.Core;
namespace WalkingTec.Mvvm.Mvc
{
public static class ActionExecutingContextExtension
{
public static void SetWtmContext(this ActionExecutingContext self)
{
var controller = self.Controller as IBaseController;
if (controller == null)
{
return;
}
if (controller.Wtm == null)
{
controller.Wtm = self.HttpContext.RequestServices.GetRequiredService<WTMContext>();
}
try
{
controller.Wtm.MSD = new ModelStateServiceProvider(self.ModelState);
controller.Wtm.Session = new SessionServiceProvider(self.HttpContext.Session);
}
catch { }
}
}
}
+25
View File
@@ -0,0 +1,25 @@
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WalkingTec.Mvvm.Mvc
{
public class FResult : ContentResult
{
public StringBuilder ContentBuilder { get; set; }
public BaseController Controller { get; set; }
public FResult() : this(string.Empty) { }
public FResult(string content)
{
ContentBuilder = new StringBuilder(content);
}
public override Task ExecuteResultAsync(ActionContext context)
{
Content = ContentBuilder.ToString();
return base.ExecuteResultAsync(context);
}
}
}
@@ -0,0 +1,100 @@
using System;
using WalkingTec.Mvvm.Core.Exceptions;
namespace WalkingTec.Mvvm.Mvc
{
public static class FResultExtension
{
/// <summary>
/// 创建一个关闭指定窗口的Result
/// </summary>
/// <param name="self">ContentResult</param>
/// <returns>返回当前对象</returns>
public static FResult CloseDialog(this FResult self)
{
self.ContentBuilder.Append("ff.CloseDialog();");
return self;
}
public static FResult Alert(this FResult self, string msg, string title = null)
{
self.ContentBuilder.Append($"ff.Alert('{msg}','{title??MvcProgram._localizer?["Sys.Info"]}');");
return self;
}
public static FResult Message(this FResult self, string msg, string title = null)
{
self.ContentBuilder.Append($"ff.Msg('{msg}','{title??MvcProgram._localizer?["Sys.Info"]}');");
return self;
}
public static FResult RefreshGrid(this FResult self, string winId = "", int index = 0)
{
if (string.IsNullOrEmpty(winId))
{
winId = self.Controller.ParentWindowId;
if (string.IsNullOrEmpty(winId))
{
winId = "LAY_app_body";
}
}
self.ContentBuilder.Append($"ff.RefreshGrid('{winId}',{index});");
return self;
}
/// <summary>
/// Layui暂时不支持单行刷新,所以现在是 RefreshGrid
/// </summary>
/// <param name="self"></param>
/// <param name="id"></param>
/// <param name="winId"></param>
/// <returns></returns>
public static FResult RefreshGridRow(this FResult self, Guid id, string winId = "")
{
self.RefreshGrid(winId);
return self;
}
public static FResult RefreshGridRow(this FResult self, string id, string winId = "")
{
self.RefreshGrid(winId);
return self;
}
public static FResult RefreshGridRow(this FResult self, long id, string winId = "")
{
self.RefreshGrid(winId);
return self;
}
/// <summary>
/// 刷新当前页面
/// </summary>
/// <param name="self"></param>
/// <returns></returns>
public static FResult RefreshPage(this FResult self)
{
self.ContentBuilder.Append($"layui.index.render();");
return self;
}
/// <summary>
/// 跳转浏览器页面
/// </summary>
/// <param name="self"></param>
/// <param name="url">url</param>
/// <returns></returns>
public static FResult RedirectUrl(this FResult self, string url)
{
self.ContentBuilder.Append($"window.location.url='{url}'");
return self;
}
public static FResult AddCustomScript(this FResult self, string script)
{
self.ContentBuilder.Append(script);
return self;
}
}
}
@@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using WalkingTec.Mvvm.Core;
namespace WalkingTec.Mvvm.Mvc
{
public static class FileExtension
{
/// <summary>
/// 生成下载文件
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="self"></param>
/// <param name="ExportName"></param>
/// <returns></returns>
public static FileContentResult GetExportData<T>(this IBasePagedListVM<T, BaseSearcher> self, string ExportName = "") where T : TopBasePoco, new()
{
self.SearcherMode = self.Ids != null && self.Ids.Count > 0 ? ListVMSearchModeEnum.CheckExport : ListVMSearchModeEnum.Export;
var data = self.GenerateExcel();
string ContentType = self.ExportExcelCount > 1 ? "application/x-zip-compresse" : "application/vnd.ms-excel";
ExportName = string.IsNullOrEmpty(ExportName) ? typeof(T).Name : ExportName;
ExportName = self.ExportExcelCount > 1 ? $"Export_{ExportName}_{DateTime.Now.ToString("yyyyMMddHHmmssffff")}.zip" : $"Export_{ExportName}_{DateTime.Now.ToString("yyyyMMddHHmmssffff")}.xlsx";
FileContentResult Result = new FileContentResult(data, ContentType);
Result.FileDownloadName = ExportName;
return Result;
}
}
}
@@ -0,0 +1,961 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Runtime.Loader;
using System.Text;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.SpaServices.ReactDevelopmentServer;
using Microsoft.AspNetCore.SpaServices.StaticFiles;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.DependencyModel;
using Microsoft.Extensions.DependencyModel.Resolution;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Auth;
using WalkingTec.Mvvm.Core.Extensions;
using WalkingTec.Mvvm.Core.Support.FileHandlers;
using WalkingTec.Mvvm.Core.Support.Json;
using WalkingTec.Mvvm.Mvc.Auth;
using WalkingTec.Mvvm.Mvc.Filters;
using WalkingTec.Mvvm.Mvc.Helper;
using WalkingTec.Mvvm.TagHelpers.LayUI;
using Microsoft.AspNetCore.SpaServices.Extensions;
using Microsoft.Extensions.FileProviders;
using WalkingTec.Mvvm.Core.Support.Quartz;
using System.Text.RegularExpressions;
namespace WalkingTec.Mvvm.Mvc
{
public static class FrameworkServiceExtension
{
//private static Configs _wtmconfigs;
//private static Configs WtmConfigs
//{
// get
// {
// if(_wtmconfigs == null)
// {
// ConfigurationBuilder cb = new ConfigurationBuilder();
// _wtmconfigs = cb.WTMConfig(null).Build().Get<Configs>();
// }
// return _wtmconfigs;
// }
//}
private static GlobalData GetGlobalData()
{
var gd = new GlobalData();
gd.AllAssembly = Utils.GetAllAssembly();
return gd;
}
private static List<SimpleMenu> GetAllMenus(List<SimpleModule> allModule, bool isQuickdebug, List<CS> connections)
{
var localizer = new ResourceManagerStringLocalizerFactory(Options.Create<LocalizationOptions>(new LocalizationOptions { ResourcesPath = "Resources" }), new Microsoft.Extensions.Logging.LoggerFactory()).Create(typeof(WalkingTec.Mvvm.Core.CoreProgram));
var menus = new List<SimpleMenu>();
if (isQuickdebug)
{
menus = new List<SimpleMenu>();
var areas = allModule.Where(x => x.NameSpace != "WalkingTec.Mvvm.Admin.Api").Select(x => x.Area?.AreaName).Distinct().ToList();
foreach (var area in areas)
{
var modelmenu = new SimpleMenu
{
ID = Guid.NewGuid(),
PageName = area ?? localizer["Sys.DefaultArea"],
TenantAllowed = true,
};
menus.Add(modelmenu);
var cModules = allModule.Where(x => x.NameSpace != "WalkingTec.Mvvm.Admin.Api" && x.Area?.AreaName == area).ToList();
foreach (var item in cModules)
{
var pages = item.Actions.Where(x => x.MethodName.ToLower() == "index" || x.ActionDes?.IsPage == true).ToList();
foreach (var page in pages)
{
var url = page.Url;
menus.Add(new SimpleMenu
{
ID = Guid.NewGuid(),
ParentId = modelmenu.ID,
PageName = item.ActionDes == null ? item.ModuleName : item.ActionDes.Description,
Url = url,
TenantAllowed = true
});
}
}
}
}
else
{
try
{
using (var dc = connections.Where(x => x.Key.ToLower() == "default").FirstOrDefault().CreateDC())
{
menus.AddRange(dc?.Set<FrameworkMenu>()
.OrderBy(x => x.DisplayOrder)
.Select(x => new SimpleMenu
{
ID = x.ID,
ParentId = x.ParentId,
PageName = x.PageName,
Url = x.Url,
DisplayOrder = x.DisplayOrder,
ShowOnMenu = x.ShowOnMenu,
Icon = x.Icon,
IsPublic = x.IsPublic,
FolderOnly = x.FolderOnly,
MethodName = x.MethodName,
IsInside = x.IsInside,
TenantAllowed = x.TenantAllowed
})
.ToList());
}
}
catch { }
}
return menus;
}
/// <summary>
/// 获取所有模块
/// </summary>
/// <param name="controllers"></param>
/// <returns></returns>
private static List<SimpleModule> GetAllModules(List<Type> controllers)
{
var modules = new List<SimpleModule>();
foreach (var ctrl in controllers)
{
var pubattr1 = ctrl.GetCustomAttributes(typeof(PublicAttribute), false);
var pubattr12 = ctrl.GetCustomAttributes(typeof(AllowAnonymousAttribute), false);
var rightattr = ctrl.GetCustomAttributes(typeof(AllRightsAttribute), false);
var debugattr = ctrl.GetCustomAttributes(typeof(DebugOnlyAttribute), false);
var areaattr = ctrl.GetCustomAttributes(typeof(AreaAttribute), false);
var mainhostonlyattr = ctrl.GetCustomAttributes(typeof(MainTenantOnlyAttribute), false);
var model = new SimpleModule
{
ClassName = ctrl.Name.Replace("Controller", string.Empty)
};
if (ctrl.Namespace == "WalkingTec.Mvvm.Mvc")
{
continue;
}
if (areaattr.Length == 0 && model.ClassName == "Home")
{
continue;
}
if (pubattr1.Length > 0 || pubattr12.Length > 0 || rightattr.Length > 0 || debugattr.Length > 0)
{
model.IgnorePrivillege = true;
}
if (mainhostonlyattr.Length > 0)
{
model.MainHostOnly = true;
}
if (typeof(BaseApiController).IsAssignableFrom(ctrl))
{
model.IsApi = true;
}
model.NameSpace = ctrl.Namespace;
//获取controller上标记的ActionDescription属性的值
var attrs = ctrl.GetCustomAttributes(typeof(ActionDescriptionAttribute), false);
if (attrs.Length > 0)
{
var ada = attrs[0] as ActionDescriptionAttribute;
var nameKey = ada.GetDescription(ctrl);
model.ModuleName = nameKey;
ada.SetLoccalizer(ctrl);
model.ActionDes = ada;
}
else
{
model.ModuleName = model.ClassName;
}
//获取该controller下所有的方法
var methods = ctrl.GetMethods(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance);
//过滤掉/Login/Login方法和特殊方法
if (model.ClassName.ToLower() == "login")
{
methods = methods.Where(x => x.IsSpecialName == false && x.Name.ToLower() != "login").ToArray();
}
else
{
methods = methods.Where(x => x.IsSpecialName == false).ToArray();
}
model.Actions = new List<SimpleAction>();
//循环所有方法
foreach (var method in methods)
{
var pubattr2 = method.GetCustomAttributes(typeof(PublicAttribute), false);
var pubattr22 = method.GetCustomAttributes(typeof(AllowAnonymousAttribute), false);
var arattr2 = method.GetCustomAttributes(typeof(AllRightsAttribute), false);
var debugattr2 = method.GetCustomAttributes(typeof(DebugOnlyAttribute), false);
var postAttr = method.GetCustomAttributes(typeof(HttpPostAttribute), false);
var mainhostonlyattr2 = method.GetCustomAttributes(typeof(MainTenantOnlyAttribute), false);
//如果不是post的方法,则添加到controller的action列表里
if (postAttr.Length == 0)
{
var action = new SimpleAction
{
Module = model,
MethodName = method.Name,
IgnorePrivillege = model.IgnorePrivillege,
MainHostOnly = model.MainHostOnly
};
if (pubattr2.Length > 0 || pubattr22.Length > 0 || arattr2.Length > 0 || debugattr2.Length > 0)
{
action.IgnorePrivillege = true;
}
if (mainhostonlyattr2.Length > 0)
{
action.MainHostOnly = true;
}
var attrs2 = method.GetCustomAttributes(typeof(ActionDescriptionAttribute), false);
if (attrs2.Length > 0)
{
var ada = attrs2[0] as ActionDescriptionAttribute;
ada.SetLoccalizer(ctrl);
action.ActionDes = ada;
}
else
{
action.ActionName = action.MethodName;
}
var pars = method.GetParameters();
if (pars != null && pars.Length > 0)
{
action.ParasToRunTest = new List<string>();
foreach (var par in pars)
{
action.ParasToRunTest.Add(par.Name);
}
}
model.Actions.Add(action);
}
}
//再次循环所有方法
foreach (var method in methods)
{
var pubattr2 = method.GetCustomAttributes(typeof(PublicAttribute), false);
var pubattr22 = method.GetCustomAttributes(typeof(AllowAnonymousAttribute), false);
var arattr2 = method.GetCustomAttributes(typeof(AllRightsAttribute), false);
var debugattr2 = method.GetCustomAttributes(typeof(DebugOnlyAttribute), false);
var mainhostonlyattr2 = method.GetCustomAttributes(typeof(MainTenantOnlyAttribute), false);
var postAttr = method.GetCustomAttributes(typeof(HttpPostAttribute), false);
//找到post的方法且没有同名的非post的方法,添加到controller的action列表里
if (postAttr.Length > 0 && model.Actions.Where(x => x.MethodName.ToLower() == method.Name.ToLower()).FirstOrDefault() == null)
{
if (method.Name.ToLower().StartsWith("dobatch"))
{
if (model.Actions.Where(x => "do" + x.MethodName.ToLower() == method.Name.ToLower()).FirstOrDefault() != null)
{
continue;
}
}
var action = new SimpleAction
{
Module = model,
MethodName = method.Name,
IgnorePrivillege = model.IgnorePrivillege,
MainHostOnly = model.MainHostOnly
};
if (pubattr2.Length > 0 || pubattr22.Length > 0 || arattr2.Length > 0 || debugattr2.Length > 0)
{
action.IgnorePrivillege = true;
}
if (mainhostonlyattr2.Length > 0)
{
action.MainHostOnly = true;
}
var attrs2 = method.GetCustomAttributes(typeof(ActionDescriptionAttribute), false);
if (attrs2.Length > 0)
{
var ada = attrs2[0] as ActionDescriptionAttribute;
ada.SetLoccalizer(ctrl);
action.ActionDes = ada;
}
else
{
action.ActionName = action.MethodName;
}
var pars = method.GetParameters();
if (pars != null && pars.Length > 0)
{
action.ParasToRunTest = new List<string>();
foreach (var par in pars)
{
action.ParasToRunTest.Add(par.Name);
}
}
model.Actions.Add(action);
}
}
if (model.Actions != null && model.Actions.Count() > 0)
{
if (areaattr.Length > 0)
{
string areaName = (areaattr[0] as AreaAttribute).RouteValue;
var existArea = modules.Where(x => x.Area?.AreaName == areaName).Select(x => x.Area).FirstOrDefault();
if (existArea == null)
{
model.Area = new SimpleArea
{
AreaName = (areaattr[0] as AreaAttribute).RouteValue,
Prefix = (areaattr[0] as AreaAttribute).RouteValue,
};
}
else
{
model.Area = existArea;
}
}
modules.Add(model);
}
}
return modules;
}
/// <summary>
/// 获取所有无需权限验证的链接
/// </summary>
/// <param name="controllers"></param>
/// <returns></returns>
private static List<string> GetAllAccessUrls(List<Type> controllers)
{
var rv = new List<string>();
foreach (var ctrl in controllers)
{
if (typeof(BaseApiController).IsAssignableFrom(ctrl))
{
continue;
}
var area = string.Empty;
var ControllerName = ctrl.Name.Replace("Controller", string.Empty);
var includeAll = false;
//获取controller上标记的ActionDescription属性的值
var attrs = ctrl.GetCustomAttributes(typeof(AllRightsAttribute), false);
var attrs2 = ctrl.GetCustomAttributes(typeof(PublicAttribute), false);
var attrs22 = ctrl.GetCustomAttributes(typeof(AllowAnonymousAttribute), false);
var areaAttr = ctrl.GetCustomAttribute(typeof(AreaAttribute), false);
if (areaAttr != null)
{
area = (areaAttr as AreaAttribute).RouteValue;
}
if (attrs.Length > 0 || attrs2.Length > 0 || attrs22.Length > 0)
{
includeAll = true;
}
//获取该controller下所有的方法
var methods = ctrl.GetMethods(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance);
//过滤掉特殊方法
methods = methods.Where(x => x.IsSpecialName == false).ToArray();
var ActionName = string.Empty;
//循环所有方法
foreach (var method in methods)
{
var postAttr = method.GetCustomAttributes(typeof(HttpPostAttribute), false);
//如果不是post的方法,则添加到controller的action列表里
if (postAttr.Length == 0)
{
ActionName = method.Name;
var url = ControllerName + "/" + ActionName;
if (!string.IsNullOrEmpty(area))
{
url = area + "/" + url;
}
url = "/" + url;
bool needadd = false;
if (includeAll == true)
{
needadd = true;
}
else
{
var attrs3 = method.GetCustomAttributes(typeof(AllRightsAttribute), false);
var attrs4 = method.GetCustomAttributes(typeof(PublicAttribute), false);
var attrs42 = method.GetCustomAttributes(typeof(AllowAnonymousAttribute), false);
if (attrs3.Length > 0 || attrs4.Length > 0 || attrs42.Length > 0)
{
needadd = true;
}
}
if (needadd)
{
rv.Add(url);
if (url.ToLower().EndsWith("/index"))
{
rv.Add(url[0..^6]);
}
}
}
}
//再次循环所有方法
foreach (var method in methods)
{
var postAttr = method.GetCustomAttributes(typeof(HttpPostAttribute), false);
//找到post的方法且没有同名的非post的方法,添加到controller的action列表里
if (postAttr.Length > 0 && !rv.Contains(ControllerName + "/" + method.Name))
{
ActionName = method.Name;
var url = ControllerName + "/" + ActionName;
if (!string.IsNullOrEmpty(area))
{
url = area + "/" + url;
}
url = "/" + url;
bool needadd = false;
if (includeAll == true)
{
needadd = true;
}
else
{
var attrs5 = method.GetCustomAttributes(typeof(AllRightsAttribute), false);
var attrs6 = method.GetCustomAttributes(typeof(PublicAttribute), false);
var attrs62 = method.GetCustomAttributes(typeof(AllowAnonymousAttribute), false);
if (attrs5.Length > 0 || attrs6.Length > 0 || attrs62.Length > 0)
{
needadd = true;
}
}
if (needadd)
{
rv.Add(url);
if (url.ToLower().EndsWith("/index"))
{
rv.Add(url[0..^6]);
}
}
}
}
}
return rv;
}
private static Assembly GetRuntimeAssembly(string name)
{
var path = Assembly.GetEntryAssembly().Location;
var library = DependencyContext.Default.RuntimeLibraries.Where(x => x.Name.ToLower() == name.ToLower()).FirstOrDefault();
if (library == null)
{
return null;
}
var r = new CompositeCompilationAssemblyResolver(new ICompilationAssemblyResolver[]
{
new AppBaseCompilationAssemblyResolver(Path.GetDirectoryName(path)),
new ReferenceAssemblyPathResolver(),
new PackageCompilationAssemblyResolver()
});
var wrapper = new CompilationLibrary(
library.Type,
library.Name,
library.Version,
library.Hash,
library.RuntimeAssemblyGroups.SelectMany(g => g.AssetPaths),
library.Dependencies,
library.Serviceable);
var assemblies = new List<string>();
r.TryResolveAssemblyPaths(wrapper, assemblies);
if (assemblies.Count > 0)
{
return AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblies[0]);
}
else
{
return null;
}
}
public static IServiceCollection AddWtmContext(this IServiceCollection services, IConfiguration config, Action<WtmContextOption> options = null)
{
var conf = config.Get<Configs>();
WtmContextOption op = new WtmContextOption();
options?.Invoke(op);
services.Configure<Configs>(config);
var gd = GetGlobalData();
services.AddHttpContextAccessor();
services.AddSingleton(gd);
services.AddLayui();
services.AddSingleton(op.DataPrivileges ?? new List<IDataPrivilege>());
DataContextFilter._csfunc = op.CsSelector;
WtmFileProvider._subDirFunc = op.FileSubDirSelector;
WTMContext.ReloadUserFunc = op.ReloadUserFunc;
services.TryAddScoped<IDataContext, NullContext>();
services.AddScoped<WTMContext>();
services.AddScoped<WtmFileProvider>();
services.Configure<FormOptions>(y =>
{
y.ValueCountLimit = 5000;
y.ValueLengthLimit = int.MaxValue - 20480;
y.MultipartBodyLengthLimit = conf.FileUploadOptions.UploadLimit;
});
services.AddHostedService<QuartzHostService>();
return services;
}
public static IServiceCollection AddWtmCrossDomain(this IServiceCollection services, IConfiguration config)
{
var conf = config.Get<Configs>();
services.AddCors(options =>
{
if (conf.CorsOptions?.Policy?.Count > 0)
{
foreach (var item in conf.CorsOptions.Policy)
{
string[] domains = item.Domain?.Split(',');
options.AddPolicy(item.Name,
builder =>
{
builder.WithOrigins(domains)
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.WithExposedHeaders("Content-Disposition");
});
}
}
else
{
options.AddPolicy("_donotusedefault",
builder =>
{
builder.SetIsOriginAllowed((a) => true)
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.WithExposedHeaders("Content-Disposition");
});
}
});
return services;
}
public static IServiceCollection AddWtmSession(this IServiceCollection services, int timeout, IConfiguration config)
{
var conf = config.Get<Configs>();
services.AddSession(options =>
{
options.Cookie.Name = conf.CookiePre + ".Session";
options.IdleTimeout = TimeSpan.FromSeconds(timeout);
});
return services;
}
public static IServiceCollection AddWtmAuthentication(this IServiceCollection services, IConfiguration config)
{
var conf = config.Get<Configs>();
services.AddScoped<ITokenService, TokenService>();
var jwtOptions = conf.JwtOptions;
var cookieOptions = conf.CookieOptions;
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = AuthConstants.JwtClaimTypes.Name,
RoleClaimType = AuthConstants.JwtClaimTypes.Role,
ValidateIssuer = true,
ValidIssuer = jwtOptions.Issuer,
ValidateAudience = true,
ValidAudience = jwtOptions.Audience,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtOptions.SecurityKey)),
LifetimeValidator = (DateTime? notBefore, DateTime? expires, SecurityToken securityToken, TokenValidationParameters validationParameters) =>
{
if(expires == null)
{
return true;
}
else
{
return expires.Value > DateTime.UtcNow;
}
},
ValidateLifetime = true
};
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
options.Cookie.Name = CookieAuthenticationDefaults.CookiePrefix + conf.CookiePre + "." + AuthConstants.CookieAuthName;
options.Cookie.HttpOnly = true;
options.Cookie.SameSite = SameSiteMode.Strict;
options.Cookie.Domain = string.IsNullOrEmpty(cookieOptions.Domain) ? null : cookieOptions.Domain;
options.ClaimsIssuer = cookieOptions.Issuer;
options.SlidingExpiration = cookieOptions.SlidingExpiration;
options.ExpireTimeSpan = TimeSpan.FromSeconds(cookieOptions.Expires);
// options.SessionStore = new MemoryTicketStore();
options.LoginPath = cookieOptions.LoginPath;
options.LogoutPath = cookieOptions.LogoutPath;
options.ReturnUrlParameter = cookieOptions.ReturnUrlParameter;
options.AccessDeniedPath = cookieOptions.AccessDeniedPath;
});
return services;
}
public static IServiceCollection AddWtmHttpClient(this IServiceCollection services, IConfiguration config)
{
var conf = config.Get<Configs>();
services.AddHttpClient();
if (conf.Domains != null)
{
foreach (var item in conf.Domains)
{
services.AddHttpClient(item.Key, x =>
{
x.BaseAddress = new Uri(item.Value.Url);
x.DefaultRequestHeaders.Add("Cache-Control", "no-cache");
x.DefaultRequestHeaders.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)");
});
}
}
return services;
}
public static IServiceCollection AddWtmSwagger(this IServiceCollection services, bool useFullName = false)
{
services.AddSwaggerGen(c =>
{
var bearer = new OpenApiSecurityScheme()
{
Description = "JWT Bearer",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey
};
c.AddSecurityDefinition("Bearer", bearer);
var sr = new OpenApiSecurityRequirement();
sr.Add(new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
}, new string[] { });
c.AddSecurityRequirement(sr);
c.SchemaFilter<SwaggerFilter>();
if (useFullName == true)
{
c.CustomSchemaIds(i => i.FullName);
}
});
return services;
}
public static IServiceCollection AddWtmMultiLanguages(this IServiceCollection services, IConfiguration config, Action<WtmLocalizationOption> op = null)
{
var conf = config.Get<Configs>();
services.AddLocalization(options => options.ResourcesPath = "Resources");
services.Configure<RequestLocalizationOptions>(options =>
{
options.DefaultRequestCulture = new RequestCulture(conf.SupportLanguages[0]);
options.SupportedCultures = conf.SupportLanguages;
options.SupportedUICultures = conf.SupportLanguages;
});
WtmLocalizationOption loc = new WtmLocalizationOption();
op?.Invoke(loc);
if (loc.LocalizationType != null)
{
services.AddSingleton<WtmLocalizationOption>(loc);
}
return services;
}
public static IMvcBuilder AddWtmDataAnnotationsLocalization(this IMvcBuilder builder, Type programType)
{
builder.AddDataAnnotationsLocalization(options =>
{
options.DataAnnotationLocalizerProvider = (type, factory) =>
{
//if (Core.CoreProgram.Buildindll.Any(x => type.FullName.StartsWith(x)))
//{
// return factory.Create(typeof(WalkingTec.Mvvm.Core.CoreProgram));
//}
//else
//{
return factory.Create(programType);
//}
};
});
return builder;
}
public static IApplicationBuilder UseWtmContext(this IApplicationBuilder app, bool isspa = false)
{
var configs = app.ApplicationServices.GetRequiredService<IOptionsMonitor<Configs>>().CurrentValue;
var lg = app.ApplicationServices.GetRequiredService<LinkGenerator>();
var gd = app.ApplicationServices.GetRequiredService<GlobalData>();
var localfactory = app.ApplicationServices.GetRequiredService<IStringLocalizerFactory>();
var lop = app.ApplicationServices.GetService<WtmLocalizationOption>();
//获取所有程序集
//var mvc = GetRuntimeAssembly("WalkingTec.Mvvm.Mvc");
//if (mvc != null && gd.AllAssembly.Contains(mvc) == false)
//{
// gd.AllAssembly.Add(mvc);
//}
//var core = GetRuntimeAssembly("WalkingTec.Mvvm.Core");
//if (core != null && gd.AllAssembly.Contains(core) == false)
//{
// gd.AllAssembly.Add(core);
//}
//var layui = GetRuntimeAssembly("WalkingTec.Mvvm.TagHelpers.LayUI");
//if (layui != null && gd.AllAssembly.Contains(layui) == false)
//{
// gd.AllAssembly.Add(layui);
//}
//set Core's _Callerlocalizer to use localizer point to the EntryAssembly's Program class
Type programType = null;
if (lop?.LocalizationType == null)
{
programType = Assembly.GetCallingAssembly()?.GetTypes()?.Where(x => x.Name == "Program").FirstOrDefault();
}
else
{
programType = lop.LocalizationType;
}
var programLocalizer = localfactory.Create(programType);
Core.CoreProgram._localizer = programLocalizer;
var controllers = gd.GetTypesAssignableFrom<IBaseController>();
var test = app.ApplicationServices.GetService<ISpaStaticFileProvider>();
gd.IsSpa = isspa == true || test != null;
gd.AllModule = GetAllModules(controllers);
var modules = Utils.ResetModule(gd.AllModule, false);
gd.CustomUserType = gd.GetTypesAssignableFrom<FrameworkUserBase>().Where(x => x.Name.ToLower() == "frameworkuser").FirstOrDefault();
gd.SetMenuGetFunc(() =>
{
var menus = new List<SimpleMenu>();
var cache = app.ApplicationServices.GetRequiredService<IDistributedCache>();
var menuCacheKey = nameof(GlobalData.AllMenus);
if (cache.TryGetValue(menuCacheKey, out List<SimpleMenu> rv) == false)
{
var data = GetAllMenus(modules, configs.IsQuickDebug, configs.Connections);
cache.Add(menuCacheKey, data, new DistributedCacheEntryOptions() { AbsoluteExpirationRelativeToNow = new TimeSpan(1, 0, 0) });
menus = data;
}
else
{
menus = rv;
}
return menus;
});
gd.SetTenantGetFunc(() =>
{
var tenants = new List<FrameworkTenant>();
var cache = app.ApplicationServices.GetRequiredService<IDistributedCache>();
var tenantsCacheKey = nameof(GlobalData.AllTenant);
if (cache.TryGetValue(tenantsCacheKey, out tenants) == false)
{
if (configs?.EnableTenant == true)
{
using (var dc = configs.Connections.Where(x => x.Key.ToLower() == "default").FirstOrDefault().CreateDC())
{
tenants = dc.Set<FrameworkTenant>().IgnoreQueryFilters().Where(x => x.Enabled).ToList();
foreach (var item in tenants)
{
if (string.IsNullOrEmpty(item.TDomain)==false)
{
Regex r = new Regex("(http://|https://)?(.+)(/)?");
var m = r.Match(item.TDomain);
if (m.Success)
{
item.TDomain = m.Groups[2].Value;
}
}
}
}
}
if(tenants == null)
{
tenants = new List<FrameworkTenant>();
}
cache.Add(tenantsCacheKey, tenants, new DistributedCacheEntryOptions() { AbsoluteExpirationRelativeToNow = new TimeSpan(1, 0, 0) });
}
return tenants;
});
foreach (var m in gd.AllModule)
{
if (isspa == false && m.IsApi == true)
{
if (m.ModuleName.ToLower().EndsWith("api") == false)
{
m.ModuleName += "Api";
}
}
foreach (var a in m.Actions)
{
string u = null;
if (a.ParasToRunTest != null && a.ParasToRunTest.Any(x => x.ToLower() == "id"))
{
u = lg.GetPathByAction(a.MethodName, m.ClassName, new { id = 0, area = m.Area?.AreaName });
}
else
{
u = lg.GetPathByAction(a.MethodName, m.ClassName, new { area = m.Area?.AreaName });
}
if (u != null && (u.EndsWith("/0")))
{
u = u.Substring(0, u.Length - 2);
if (m.IsApi == true)
{
u = u + "/{id}";
}
}
if (u != null && (u.ToLower().EndsWith("?id=0")))
{
u = u[0..^5];
if (m.IsApi == true)
{
u = u + "/{id}";
}
}
a.Url = u;
}
}
gd.AllAccessUrls = gd.AllModule.SelectMany(x => x.Actions).Where(x => x.IgnorePrivillege == true || x.Module.IgnorePrivillege == true).Select(x => x.Url).ToList();
gd.AllMainTenantOnlyUrls = gd.AllModule.SelectMany(x => x.Actions).Where(x => x.MainHostOnly == true || x.Module.MainHostOnly == true).Select(x => x.Url).ToList();
WtmFileProvider.Init(configs, gd);
using (var scope = app.ApplicationServices.CreateScope())
{
var fixdc = scope.ServiceProvider.GetRequiredService<IDataContext>();
if (fixdc is NullContext)
{
var cs = configs.Connections;
foreach (var item in cs)
{
var dc = item.CreateDC();
dc.DataInit(gd.AllModule, isspa == true || test != null).Wait();
}
}
else
{
fixdc.DataInit(gd.AllModule, isspa == true || test != null).Wait();
}
}
return app;
}
public static IApplicationBuilder UseWtmMultiLanguages(this IApplicationBuilder app)
{
var configs = app.ApplicationServices.GetRequiredService<IOptionsMonitor<Configs>>().CurrentValue;
if (string.IsNullOrEmpty(configs.Languages) == false)
{
app.UseRequestLocalization(new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture(configs.SupportLanguages[0]),
SupportedCultures = configs.SupportLanguages,
SupportedUICultures = configs.SupportLanguages
});
System.Threading.Thread.CurrentThread.CurrentCulture = configs.SupportLanguages[0];
System.Threading.Thread.CurrentThread.CurrentUICulture = configs.SupportLanguages[0];
}
return app;
}
public static IApplicationBuilder UseWtmCrossDomain(this IApplicationBuilder app)
{
var configs = app.ApplicationServices.GetRequiredService<IOptionsMonitor<Configs>>().CurrentValue;
if (configs.CorsOptions.EnableAll == true)
{
if (configs.CorsOptions?.Policy?.Count > 0)
{
app.UseCors(configs.CorsOptions.Policy[0].Name);
}
else
{
app.UseCors("_donotusedefault");
}
}
return app;
}
public static IApplicationBuilder UseWtmStaticFiles(this IApplicationBuilder app)
{
app.UseStaticFiles(new StaticFileOptions
{
RequestPath = new PathString("/_js"),
FileProvider = new EmbeddedFileProvider(
typeof(_CodeGenController).GetTypeInfo().Assembly,
"WalkingTec.Mvvm.Mvc")
});
return app;
}
public static IApplicationBuilder UseWtmSwagger(this IApplicationBuilder app, bool showInDebugOnly = true)
{
var configs = app.ApplicationServices.GetRequiredService<IOptions<Configs>>().Value;
if (configs.IsQuickDebug == true || showInDebugOnly == false)
{
}
return app;
}
public static IApplicationBuilder UseReact(this IApplicationBuilder app)
{
var env = app.ApplicationServices.GetService<IWebHostEnvironment>();
app.UseSpaStaticFiles();
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
});
return app;
}
}
}
@@ -0,0 +1,27 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Linq;
namespace WalkingTec.Mvvm.Mvc
{
public static class HttpContextExtention
{
/// <summary>
/// 客户端 Ip 头
/// </summary>
public const string REMOTE_IP_HEADER = "X-Forwarded-For";
public static string GetRemoteIpAddress(this HttpContext self)
{
var proxyIp = self.Request?.Headers?[REMOTE_IP_HEADER].FirstOrDefault();
if (!string.IsNullOrEmpty(proxyIp))
{
return proxyIp;
}
else
{
return self.Connection.RemoteIpAddress.ToString();
}
}
}
}
@@ -0,0 +1,109 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using WalkingTec.Mvvm.Core;
namespace WalkingTec.Mvvm.Mvc
{
public static class IconFontsHelper
{
private static List<ComboSelectListItem> _iconFontItems;
public static List<ComboSelectListItem> IconFontItems
{
get
{
foreach (var item in _iconFontItems.Where(x => x.Selected == true))
item.Selected = false;
return _iconFontItems;
}
}
private static Dictionary<string, List<MenuItem>> _iconFontDicItems;
public static Dictionary<string, List<MenuItem>> IconFontDicItems => _iconFontDicItems;
public static void GenerateIconFont(params string[] dirs)
{
var baseDirs = new string[] { "wwwroot/font", "wwwroot/layui" };
if(dirs.Length > 0)
{
baseDirs = dirs;
}
var iconFontHashSet = new HashSet<string>();
var IconFontDic = new Dictionary<string, string[]>();
foreach (var dir in baseDirs)
{
if (Directory.Exists(dir))
{
RecursiveDir(dir, iconFontHashSet, IconFontDic);
}
}
var iconFonts = iconFontHashSet.ToArray();
_iconFontItems = iconFontHashSet.Select(x => new ComboSelectListItem
{
Text = x,
Value = x,
Icon = x
}).ToList();
_iconFontDicItems = new Dictionary<string, List<MenuItem>>();
foreach (var key in IconFontDic.Keys)
{
IconFontDicItems.Add(key, IconFontDic[key].Select(x => new MenuItem
{
Text = x,
Value = x,
Icon = $"{key} {x}"
}).ToList());
}
}
private static void RecursiveDir(string dirPath, HashSet<string> iconFonts, Dictionary<string, string[]> iconFontDic)
{
var dirs = Directory.GetDirectories(dirPath);
foreach (var dir in dirs)
{
RecursiveDir(dir, iconFonts, iconFontDic);
}
var files = Directory.GetFiles(dirPath, "*.css");
foreach (var cssPath in files)
{
ResolveIconfont(cssPath, iconFonts, iconFontDic);
}
}
/// <summary>
/// 解析
/// </summary>
private static void ResolveIconfont(string cssPath, HashSet<string> iconFonts, Dictionary<string, string[]> iconFontDic)
{
var file = File.ReadAllText(cssPath).Replace("\r\n", string.Empty);
// 找到自定义的 iconfont
var regex = new Regex("@font-face\\s{0,}{\\s{0,}('|\"|)font-family(\\1)\\s{0,}:\\s{0,}('|\"|)([a-zA-Z0-9-_.#]{1,})(\\3)\\s{0,};");
var iconMatchs = regex.Matches(file);
foreach (Match iconfontItem in iconMatchs)
{
// icon family name
var iconName = iconfontItem.Groups[4].ToString();
var itemRegex = new Regex($".({iconName}-([a-zA-Z0-9-_.#]{{1,}}))\\s{{0,}}:before\\s{{0,}}{{");
var itemMatchs = itemRegex.Matches(file);
var iconFontItems = new List<string>();
foreach (Match item in itemMatchs)
{
iconFontItems.Add(item.Groups[1].ToString());
}
if (iconFontItems.Count > 0)
{
iconFonts.Add(iconName);
iconFontDic.Add(iconName, iconFontItems.OrderBy(x => x).ToArray());
}
}
}
}
}
@@ -0,0 +1,27 @@
using System;
using System.Threading.Tasks;
using Quartz;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;
using WalkingTec.Mvvm.Core.Support.Quartz;
namespace WalkingTec.Mvvm.Mvc.Helper
{
//[QuartzRepeat(3600,0,true)]
//[QuartzJob("RefreshJwt")]
//[QuartzGroup("Wtm_System")]
//public class JwtRefreshJob : WtmJob
//{
// public override Task Execute(IJobExecutionContext context)
// {
// try
// {
// var sql = $"DELETE FROM {this.Wtm.DC.GetTableName<PersistedGrant>()} WHERE Expiration<'{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}'";
// this.Wtm.DC.RunSQL(sql);
// Wtm.DoLog("清理过期的refreshToken", ActionLogTypesEnum.Job,"Wtm_System","RefreshJwt");
// }
// catch { }
// return Task.CompletedTask;
// }
//}
}
@@ -0,0 +1,36 @@
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WalkingTec.Mvvm.Core;
namespace WalkingTec.Mvvm.Mvc
{
public static class ModelStateExtension
{
public static ErrorObj GetErrorJson(this ModelStateDictionary self)
{
var mse = new ErrorObj();
mse.Form = new Dictionary<string, string>();
mse.Message = new List<string>();
foreach (var item in self)
{
if (item.Value.ValidationState == ModelValidationState.Invalid)
{
var name = item.Key;
if (name.ToLower().StartsWith(" ") == false && name != "")
{
mse.Form.Add(name, item.Value.Errors.FirstOrDefault()?.ErrorMessage);
}
else
{
mse.Message.Add(item.Value.Errors.FirstOrDefault()?.ErrorMessage);
}
}
}
return mse;
}
}
}
@@ -0,0 +1,73 @@
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WalkingTec.Mvvm.Core;
namespace WalkingTec.Mvvm.Mvc
{
/// <summary>
/// 模拟MVC中的ModelState类
/// </summary>
public class ModelStateServiceProvider : IModelStateService
{
private ModelStateDictionary _states;
public ModelStateServiceProvider(ModelStateDictionary s)
{
this._states = s;
}
public List<MsdError> this[string name]
{
get
{
return _states?[name].Errors.Select(x => new MsdError { ErrorMessage = x.ErrorMessage, Exception = x.Exception }).ToList();
}
}
/// <summary>
/// 添加错误信息
/// </summary>
/// <param name="key">错误的字段名</param>
/// <param name="errorMessage">错误信息</param>
public void AddModelError(string key, string errorMessage)
{
if (string.IsNullOrEmpty(key))
{
key = Guid.NewGuid().ToString();
}
_states.AddModelError(key, errorMessage);
}
public void RemoveModelError(string key)
{
_states.Remove(key);
}
public void Clear()
{
_states.Clear();
}
public int Count => _states.Count;
public IEnumerable<string> Keys => _states.Keys;
bool IModelStateService.IsValid => _states.IsValid;
public string GetFirstError()
{
string rv = "";
foreach (var key in Keys)
{
if(this[key].Count > 0){
rv = this[key].First().ErrorMessage;
}
}
return rv;
}
}
}
@@ -0,0 +1,85 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Localization;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Json;
using WalkingTec.Mvvm.Mvc.Binders;
using WalkingTec.Mvvm.Mvc.Filters;
namespace WalkingTec.Mvvm.Mvc
{
public static class MvcOptionExtension
{
public static void UseWtmMvcOptions(this MvcOptions options)
{
// ModelBinderProviders
options.ModelBinderProviders.Insert(0, new StringBinderProvider());
// Filters
options.Filters.Add(new DataContextFilter());
options.Filters.Add(new PrivilegeFilter());
options.Filters.Add(new FrameworkFilter());
options.ModelBindingMessageProvider.SetValueIsInvalidAccessor((x) => Core.CoreProgram._localizer?["Sys.ValueIsInvalidAccessor", x]);
options.ModelBindingMessageProvider.SetAttemptedValueIsInvalidAccessor((x, y) => Core.CoreProgram._localizer?["Sys.AttemptedValueIsInvalidAccessor", x, y]);
options.ModelBindingMessageProvider.SetValueMustNotBeNullAccessor((x) => Core.CoreProgram._localizer?["Sys.ValueIsInvalidAccessor", x]);
options.ModelMetadataDetailsProviders.Add(new ExcludeBindingMetadataProvider(typeof(IModelStateService)));
options.ModelMetadataDetailsProviders.Add(new ExcludeBindingMetadataProvider(typeof(IDataContext)));
options.ModelMetadataDetailsProviders.Add(new ExcludeBindingMetadataProvider(typeof(WTMContext)));
options.ModelMetadataDetailsProviders.Add(new ExcludeBindingMetadataProvider(typeof(Configs)));
options.ModelMetadataDetailsProviders.Add(new ExcludeBindingMetadataProvider(typeof(GlobalData)));
options.ModelMetadataDetailsProviders.Add(new ExcludeBindingMetadataProvider(typeof(IDistributedCache)));
options.ModelMetadataDetailsProviders.Add(new ExcludeBindingMetadataProvider(typeof(LoginUserInfo)));
options.ModelMetadataDetailsProviders.Add(new ExcludeBindingMetadataProvider(typeof(ISessionService)));
options.ModelMetadataDetailsProviders.Add(new ExcludeBindingMetadataProvider(typeof(IModelStateService)));
options.ModelMetadataDetailsProviders.Add(new ExcludeBindingMetadataProvider(typeof(IUIService)));
options.ModelMetadataDetailsProviders.Add(new ExcludeBindingMetadataProvider(typeof(IStringLocalizer)));
options.EnableEndpointRouting = true;
}
public static void UseWtmJsonOptions(this JsonOptions options)
{
options.JsonSerializerOptions.PropertyNamingPolicy = null;
options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
options.JsonSerializerOptions.NumberHandling = JsonNumberHandling.AllowReadingFromString | JsonNumberHandling.WriteAsString;
options.JsonSerializerOptions.AllowTrailingCommas = true;
options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());
options.JsonSerializerOptions.Converters.Add(new StringIgnoreLTGTConverter());
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
options.JsonSerializerOptions.Converters.Add(new BoolStringConverter());
options.JsonSerializerOptions.Converters.Add(new DateRangeConverter());
options.JsonSerializerOptions.Converters.Add(new PocoConverter());
options.JsonSerializerOptions.Converters.Add(new TypeConverter());
options.JsonSerializerOptions.Converters.Add(new DynamicDataConverter());
Core.CoreProgram.DefaultJsonOption = options.JsonSerializerOptions;
JsonSerializerOptions jsonOptions2 = new JsonSerializerOptions();
jsonOptions2.PropertyNamingPolicy = null;
jsonOptions2.NumberHandling = JsonNumberHandling.AllowReadingFromString | JsonNumberHandling.WriteAsString;
jsonOptions2.AllowTrailingCommas = true;
jsonOptions2.Converters.Add(new DateTimeConverter());
jsonOptions2.Converters.Add(new JsonStringEnumConverter());
jsonOptions2.Converters.Add(new BoolStringConverter());
jsonOptions2.Converters.Add(new DateRangeConverter());
jsonOptions2.Converters.Add(new PocoConverter());
jsonOptions2.Converters.Add(new TypeConverter());
jsonOptions2.Converters.Add(new DynamicDataConverter());
CoreProgram.DefaultPostJsonOption = jsonOptions2;
}
public static void UseWtmApiOptions(this ApiBehaviorOptions options)
{
options.SuppressModelStateInvalidFilter = true;
options.InvalidModelStateResponseFactory = (a) =>
{
return new BadRequestObjectResult(a.ModelState.GetErrorJson());
};
}
}
}
@@ -0,0 +1,79 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using WalkingTec.Mvvm.Core;
namespace WalkingTec.Mvvm.Mvc
{
public static class RequestExtension
{
public static async Task<IActionResult> RedirectCall(this HttpRequest baserequest, WTMContext wtm, string url = null)
{
var request = baserequest ?? wtm.HttpContext.Request;
HttpMethodEnum method = Enum.Parse<HttpMethodEnum>(request.Method.ToString());
if (string.IsNullOrEmpty(url))
{
url = request.Path.ToString();
}
url += request.QueryString;
ApiResult<string> rv = null;
if (method == HttpMethodEnum.GET)
{
rv = await wtm.CallAPI("mainhost", url);
}
else
{
if(request.HasFormContentType == true)
{
Dictionary<string, string> data = new Dictionary<string, string>();
foreach (var item in request.Form)
{
data.Add(item.Key, item.Value);
}
rv = await wtm.CallAPI<string>("mainhost", url, method, data);
}
else
{
string s = "";
if (request.HttpContext?.Items?.ContainsKey("DONOTUSE_REQUESTBODY")==true)
{
s = request.HttpContext.Items["DONOTUSE_REQUESTBODY"].ToString();
}
HttpContent data = new StringContent(s, System.Text.Encoding.UTF8, "application/json");
rv = await wtm.CallAPI<string>("mainhost", url, method, data);
}
}
return rv.ToActionResult();
}
public static IActionResult ToActionResult(this ApiResult<string> self)
{
if(self == null)
{
return new BadRequestResult();
}
if (self.StatusCode == System.Net.HttpStatusCode.OK)
{
return new OkObjectResult(self.Data);
}
else if (self.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
return new UnauthorizedResult();
}
else if (self.StatusCode == System.Net.HttpStatusCode.Forbidden)
{
return new ForbidResult();
}
else if (self.StatusCode == System.Net.HttpStatusCode.BadRequest)
{
return new BadRequestObjectResult(self.Errors);
}
return new BadRequestResult();
}
}
}
@@ -0,0 +1,21 @@
using System.Text.Json;
using Microsoft.AspNetCore.Http;
namespace WalkingTec.Mvvm.Mvc
{
public static class SessionExtensions
{
public static void Set<T>(this ISession session, string key, T value)
{
session.SetString(key, JsonSerializer.Serialize(value));
session.CommitAsync().Wait();
}
public static T Get<T>(this ISession session, string key)
{
var value = session.GetString(key);
return value == null ? default(T) :
JsonSerializer.Deserialize<T>(value);
}
}
}
@@ -0,0 +1,34 @@
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Text;
using WalkingTec.Mvvm.Core;
namespace WalkingTec.Mvvm.Mvc
{
public class SessionServiceProvider : ISessionService
{
private ISession _inner { get; set; }
public SessionServiceProvider(ISession s)
{
_inner = s;
}
public T Get<T>(string key)
{
return _inner.Get<T>(key);
}
public void Set<T>(string key, T val)
{
_inner.Set<T>(key, val);
}
public string SessionId
{
get
{
return _inner.Id;
}
}
}
}
@@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Filters;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Support.FileHandlers;
namespace WalkingTec.Mvvm.Mvc.Helper
{
public class WtmContextOption
{
/// <summary>
/// A Func that return ConnectionString key name, used for multi database program to select a db at run time
/// </summary>
public Func<ActionExecutingContext, string> CsSelector { get; set; }
/// <summary>
/// Set the data privileges that this system support
/// </summary>
public List<IDataPrivilege> DataPrivileges { get; set; }
/// <summary>
/// Set the sub directory of uploaded file, if you want to save file in different directories according to datetime or other properties, use this selector
/// </summary>
public Func<IWtmFileHandler, string> FileSubDirSelector { get; set; }
public Func<WTMContext,string,LoginUserInfo> ReloadUserFunc { get; set; }
}
}
@@ -0,0 +1,74 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.Options;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;
namespace WalkingTec.Mvvm.Mvc
{
public class WtmMiddleware
{
private readonly RequestDelegate _next;
public WtmMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context, WTMContext wtm)
{
var max = context.Features.Get<IHttpMaxRequestBodySizeFeature>();
if (max.IsReadOnly == false)
{
max.MaxRequestBodySize = wtm.ConfigInfo.FileUploadOptions.UploadLimit;
}
if (context.Request.Path == "/")
{
context.Response.Cookies.Append("pagemode", wtm.ConfigInfo.PageMode.ToString());
context.Response.Cookies.Append("tabmode", wtm.ConfigInfo.TabMode.ToString());
}
if (context.Request.ContentLength > 0 && context.Request.HasFormContentType == false)
{
try
{
context.Request.EnableBuffering();
context.Request.Body.Position = 0;
StreamReader tr = new StreamReader(context.Request.Body);
string body = tr.ReadToEndAsync().Result;
context.Request.Body.Position = 0;
if (context.Items.ContainsKey("DONOTUSE_REQUESTBODY") == false)
{
context.Items.Add("DONOTUSE_REQUESTBODY", body);
}
else
{
context.Items["DONOTUSE_REQUESTBODY"] = body;
}
}
catch {
context.Request.Body.Position = 0;
}
}
await _next(context);
if (context.Response.StatusCode == 404)
{
await context.Response.WriteAsync(string.Empty);
}
}
}
public static class WtmMiddlewareExtensions
{
public static IApplicationBuilder UseWtm(
this IApplicationBuilder builder)
{
return builder.UseMiddleware<WtmMiddleware>();
}
}
}