using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure;
using Util.Helpers;
using Util.Webs.Filters;
namespace Util.Samples.RazorPageExtensions {
///
/// Page静态Html生成器
///
public class PageHtmlGenerator : IHtmlGenerator {
///
/// 操作描述集合提供程序
///
private readonly IActionDescriptorCollectionProvider _actionDescriptorCollectionProvider;
///
/// 页面加载器
///
private readonly IPageLoader _pageLoader;
///
/// 初始化一个类型的实例
///
/// 操作描述集合提供程序
/// 页面加载器
public PageHtmlGenerator( IActionDescriptorCollectionProvider actionDescriptorCollectionProvider,
IPageLoader pageLoader ) {
_actionDescriptorCollectionProvider = actionDescriptorCollectionProvider;
_pageLoader = pageLoader;
}
///
/// 构建并生成Html
///
public async Task BuildAsync() {
var pageActionDescriptors = GetPageActionDescriptors();
var requestUrl = $"{Web.Request.Scheme}://{Web.Request.Host}";
foreach ( var actionDescriptor in pageActionDescriptors ) {
if ( actionDescriptor.RelativePath.ToLower() == "/Pages/Index.cshtml".ToLower() ) {
continue;
}
var compiledPage = _pageLoader.Load( actionDescriptor );
var path = actionDescriptor.ViewEnginePath;// Url访问路径:/Components/DataDisplay/Table
var htmlPath = GetHtmlPathAttribute( compiledPage );
if ( htmlPath != null ) {
if ( htmlPath.Ignore ) {
continue;
}
}
await Web.Client().Get( $"{requestUrl}/view{path}" ).ResultAsync();
}
}
///
/// 获取页面操作描述
///
private IEnumerable GetPageActionDescriptors() {
return this._actionDescriptorCollectionProvider.ActionDescriptors.Items.OfType();
}
///
/// 获取Html生成路径特性
///
/// 编译后的页面
private HtmlPathAttribute GetHtmlPathAttribute( CompiledPageActionDescriptor compiledPage ) =>
compiledPage.PageTypeInfo.GetCustomAttribute() ??
compiledPage.DeclaredModelTypeInfo.GetCustomAttribute();
}
}