using System; using System.IO; using System.Text; using System.Threading.Tasks; using Hncore.Infrastructure.EF; using Hncore.Infrastructure.Extension; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.Razor; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewEngines; using Microsoft.AspNetCore.Mvc.ViewFeatures; using Microsoft.AspNetCore.Routing; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.Extensions.DependencyInjection; namespace Hncore.Infrastructure.WebApi { [ApiController] public class HncoreControllerBase : ControllerBase { protected ApiResult Success() { return new ApiResult(ResultCode.C_SUCCESS, ""); } protected ApiResult Success(T data, string message = "") { return new ApiResult(ResultCode.C_SUCCESS, message) {Data = data}; } protected ApiResult Error(string message = "") { return new ApiResult(ResultCode.C_UNKNOWN_ERROR, message); } protected ApiResult Error(ResultCode code, string message = "") { return new ApiResult(code, message); } protected ApiResult UofCommit(string message = "") { RepositoryDbContext.SaveChanges(); return Success(message); } protected ApiResult UofCommit(Func func, string message = "") { RepositoryDbContext.SaveChanges(); return Success(func(), message); } protected async Task UofCommitAsync(string message = "") { await RepositoryDbContext.SaveChangesAsync(); return Success(message); } protected async Task UofCommitAsync(IDbContextTransaction trans, string message = "") { await RepositoryDbContext.SaveChangesAsync(); trans.Commit(); return Success(message); } protected async Task UofCommitAsync(Func func, string message = "") { await RepositoryDbContext.SaveChangesAsync(); return Success(func(), message); } protected DbContext RepositoryDbContext => Request.HttpContext .RequestServices .GetService() .DbContext; protected async Task RenderViewToStringAsync(string viewName, object model = null) { using (var sw = new StringWriter()) { var actionContext = new ActionContext(HttpContext, new RouteData(), new ActionDescriptor()); var viewResult = HttpContext.RequestServices.GetService() .FindView(actionContext, viewName, false); if (viewResult.View == null) { throw new ArgumentNullException($"未找到视图{viewName}"); } var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()) { Model = model }; var viewContext = new ViewContext( actionContext, viewResult.View, viewDictionary, new TempDataDictionary(actionContext.HttpContext, HttpContext.RequestServices.GetService()), sw, new HtmlHelperOptions() ); await viewResult.View.RenderAsync(viewContext); return sw.ToString().HtmlDecode(); } } } }