c# - ASP.NET Core - 从类库查看

标签 c# asp.net-core asp.net-core-middleware asp.net-core-3.0

我试图使我的 asp.net 核心项目完全模块化。 所以我对一些功能进行了分组,并将它们分离到不同的类库中。 通过这种结构,我可以通过在 asp.net 项目中添加/删除 dll 引用来激活/停用功能。

C# 部分工作正常。 images/js/css/html 等内容文件也构建在输出文件夹中,可以毫无问题地在 html 中引用。

但是如何使用 html 文件作为我的 razor View ?

示例类库 (NoteModule):https://i.ibb.co/tb7fbxg/so-1.png


程序.cs

public static class Program
    {
        public static void Main(string[] args)
        {
            var assembly = Assembly.GetEntryAssembly();
            var assemblyLocation = assembly.Location;
            var assemblyPath = Path.GetDirectoryName(assemblyLocation);

            var builder = Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(x => x.UseWebRoot(assemblyPath).UseStartup<Startup>());
            var build = builder.Build();
            build.Run();
        }
    }

启动.cs

public class Startup
    {
        public IConfiguration Configuration { get; }

        public Startup(IConfiguration configuration)
        {
            this.Configuration = configuration;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddRazorPages();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseDefaultFiles(new DefaultFilesOptions
            {
                FileProvider = new PhysicalFileProvider(Path.Combine(env.WebRootPath, "Views")),
                RequestPath = "/Views",
            });
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(Path.Combine(env.WebRootPath, "Assets")),
                RequestPath = "/Assets",
            });
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(Path.Combine(env.WebRootPath, "Views")),
                RequestPath = "/Views",
            });

            //app.UseMiddleware<ContentMiddleware>();
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(x =>
            {
                x.MapControllerRoute("default", "{controller=" + Constants.ROUTE_DEFAULT_CONTROLLER + "}/{action=" + Constants.ROUTE_DEFAULT_ACTION + "}/{id?}");
                x.MapRazorPages();
            });
        }
    }

我试图通过自定义中间件从文件路径将 html 数据注入(inject)到响应流中。 但这样 Razor-Commands 就不会被执行。

我该如何解决?有没有更简单的方法?

ContentMiddleware.cs

    public class ContentMiddleware
    {
        private RequestDelegate Next { get; }
        private IWebHostEnvironment Environment { get; }

        public ContentMiddleware(RequestDelegate next, IWebHostEnvironment env)
        {
            this.Next = next;
            this.Environment = env;
        }

        public async Task Invoke(HttpContext context)
        {
            var route = context.Request.Path.Value.Substring(1).Replace("/", "\\");
            var contentDirectory = Path.Combine(this.Environment.WebRootPath, "Views");
            var contentPath = new FileInfo(Path.Combine(contentDirectory, $"{route}.cshtml"));

            var buffer = await File.ReadAllBytesAsync(contentPath.FullName);

            context.Response.StatusCode = (int)HttpStatusCode.OK;
            context.Response.ContentLength = buffer.Length;
            context.Response.ContentType = "text/html";

            using (var stream = context.Response.Body)
            {
                await stream.WriteAsync(buffer, default, buffer.Length);
                await stream.FlushAsync();
            }

            await this.Next(context);
        }
    }

最佳答案

经过两天的研究,我得到了答案:

类库是不够的。您需要一个 Razor 类库。

或者您可以编辑您的 .csproj:

// from
<Project Sdk="Microsoft.NET.Sdk">
// to
<Project Sdk="Microsoft.NET.Sdk.Razor">
// from
  <PropertyGroup>
    <TargetFramework>netcoreapp3.0</TargetFramework>
  </PropertyGroup>
// to
  <PropertyGroup>
    <TargetFramework>netcoreapp3.0</TargetFramework>
    <AddRazorSupportForMvc>true</AddRazorSupportForMvc>
  </PropertyGroup>

关于c# - ASP.NET Core - 从类库查看,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57617180/

相关文章:

c# - 在 ASP.NET Core 的中间件中注入(inject)服务

c# - 如果 UseSpaStaticFiles() 应该服务于 Angular 页面,为什么仍然需要 UseSpa()?

c# - 当验证需要数据库时,BL 与 DAL

c# - 将多个参数从一个页面发送到另一个页面

c# - 如何使用 let 在 LINQ 查询中定义一组新数据?

c# - .net C# 的多值分隔符

asp.net-core - Asp.net Core 中内存使用的限制

c# - ASP.NET Core EF Code First appsettings.json

asp.net-core - System.Runtime, Version=4.2.1.0, PublicKeyToken=b03f5f7f11d50a3a 的版本高于引用的程序集

asp.net-core - 我需要在 ASP.NET Core 中调用 AddMemoryCache 才能让缓存工作吗?