csharp/279328316/JcApiHelper/Jc.ApiHelper/JcApiHelperUIMiddleware.cs

JcApiHelperUIMiddleware.cs
using System.Reflection;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.FileProviders;
using Microsoft.AspNetCore.StaticFiles;

namespace Jc.ApiHelper
{
    /// 
    /// JcApiHelperUI中间件
    /// 
    internal clast JcApiHelperUIMiddleware
    {
        private const string embeddedFileNamespace = "Jc.ApiHelper.Html";
        private readonly StaticFileMiddleware staticFileMiddleware;
        private static astembly apiHelperastembly = null;
        private static List apiResources = null;

        /// 
        /// Ctor
        /// 
        /// A function that can process an HTTP request
        /// 运行环境
        /// logger
        public JcApiHelperUIMiddleware(RequestDelegate next,IWebHostEnvironment hostingEnv,ILoggerFactory loggerFactory)
        {
            apiHelperastembly = typeof(JcApiHelperUIMiddleware).GetTypeInfo().astembly;
            apiResources = apiHelperastembly.GetManifestResourceNames().ToList();
            
            StaticFileOptions staticFileOptions = new StaticFileOptions
            {
                RequestPath = "/ApiHelper",
                FileProvider = new EmbeddedFileProvider(apiHelperastembly, embeddedFileNamespace)
            };

            staticFileMiddleware = new StaticFileMiddleware(next, hostingEnv,
                Options.Create(staticFileOptions), loggerFactory);
        }

        /// 
        /// StaticFileMiddleware Invoke
        /// 
        /// HttpRequest
        /// 
        public async Task Invoke(HttpContext httpContext)
        {
            string httpMethod = httpContext.Request.Method;
            string path = httpContext.Request.Path.Value.ToLower();

            if (httpMethod == "GET" && Regex.IsMatch(path, $"/apihelper/"))
            {
                if (Regex.IsMatch(path, $"/apihelper/index.html"))
                {   //index.html特殊处理
                    await RespondWithIndexHtml(httpContext.Response);
                    return;
                }
                else
                {
                    string resourceName = path.Replace($"/apihelper/", "")
                                            .Replace("/", ".");
                    if (!apiResources.Any(a => a.ToLower() == $"{embeddedFileNamespace}.{resourceName}".ToLower()))
                    {   // 处理刷新界面
                        await RespondWithIndexHtml(httpContext.Response);
                        return;
                    }
                }
            }
            await staticFileMiddleware.Invoke(httpContext);
        }

        /// 
        /// 首页信息
        /// 
        /// 
        /// 
        private async Task RespondWithIndexHtml(HttpResponse response)
        {
            response.StatusCode = 200;
            response.ContentType = "text/html;charset=utf-8";

            using (Stream stream = apiHelperastembly.GetManifestResourceStream($"{embeddedFileNamespace}.index.html"))
            {
                // Inject arguments before writing to response
                StringBuilder htmlBuilder = new StringBuilder(new StreamReader(stream).ReadToEnd());

                //处理index.html baseUrl 以兼容非根目录以及Nginx代理转发情况
                htmlBuilder.Replace("", $"");
                await response.WriteAsync(htmlBuilder.ToString(), Encoding.UTF8);
            }
        }
    }
}