代码改变世界

在 ASP.NET Core 中使用 ApplicationPart 的简单示例

2019-09-25 11:48  音乐让我说  阅读(1406)  评论(0编辑  收藏  举报

1. 项目截图:

 

 

2. 代码

 

 

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netcoreapp2.2</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <Content Include="Views\MyShared\Index.cshtml">
      <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
    </Content>
  </ItemGroup>

  <ItemGroup>
    <EmbeddedResource Include="Views\**\*.cshtml" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.App" />
  </ItemGroup>

</Project>

请注意这里的 <EmbeddedResource Include="Views\**\*.cshtml" />

 

    public class StartupViews
    {
        public StartupViews(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        #region snippet
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<RazorViewEngineOptions>(options =>
            {
                options.FileProviders.Add(
                 new EmbeddedFileProvider(typeof(MySharedController).GetTypeInfo().Assembly));
            });
            // Requires using System.Reflection;
            var assembly = typeof(MySharedController).GetTypeInfo().Assembly;
            services.AddMvc()
                .AddApplicationPart(assembly)
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
        #endregion

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }

 

 

 

 

 

谢谢浏览!