【问题标题】:How to use a frontend controller in another assembly in ASP.NET Core MVC 2.0?如何在 ASP.NET Core MVC 2.0 的另一个程序集中使用前端控制器?
【发布时间】:2018-07-12 08:21:34
【问题描述】:

我有一个 ASP.NET MVC 项目,我想从另一个程序集中添加一些图形前端页面。这个问题和这个问题类似:How to use a controller in another assembly in ASP.NET Core MVC 2.0?

我已经添加了建议的代码:

services.AddMvc().AddApplicationPart(assembly).AddControllersAsServices();

我添加了 Visual Studio 创建的示例 MVC 项目以及“HomeController”。 并调用了新的 HomeController 。 (当我独立运行时,示例项目能够正常显示。)

但是当我通过我的主项目运行它时,它给出了以下异常:

处理请求时发生未处理的异常。 InvalidOperationException:未找到视图“索引”。搜索了以下位置:

/Views/Home/Index.cshtml

/Views/Shared/Index.cshtml

/Pages/Shared/Index.cshtml

Microsoft.AspNetCore.Mvc.ViewEngines.ViewEngineResult.EnsureSuccessful(IEnumerable originalLocations)

HomeController中的 Index 函数被找到并触发。 (我可以在其中设置一个断点。)但似乎没有执行来自外部程序集的内部设置。 (或其他东西。)第二个程序集的启动代码未执行。它应该,我猜?缺少什么?

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(o => o.AddPolicy("Local", builder =>
    {
        builder.AllowAnyOrigin()
               .AllowAnyMethod()
               .AllowAnyHeader();
    }));
    //...
    services.AddSingleton<IDataviewer>(_dataviewer);
    services.AddSingleton<IUserAccessManager>(_userAccessManager);
    services.AddSingleton<ITokenLinkManager>(_tokenLinkManager);
    services.AddSingleton<IEmailManager>(_emailManager);
    services.AddMvc().AddApplicationPart(typeof(UserAdministration.Program).Assembly).AddControllersAsServices();
}

我的配置如下所示:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime appLifetime)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    app.UseCors("Local");
    app.UseMvcWithDefaultRoute();
}

我认为,我的其余代码不应该是相关的。 (这是一个相当基础的项目。)

【问题讨论】:

  • 它正在尝试查找不存在的视图。您在错误中的这些文件夹中是否有 Index.cshtml?
  • 是的,Microsoft 的示例项目在单独运行时运行良好

标签: c# asp.net-core-mvc


【解决方案1】:

我想我已经找到了一些答案。我可能需要在我的配置函数中添加类似这样的内容:

var embeddedFileProvider = new Microsoft.Extensions.FileProviders.EmbeddedFileProvider(
    typeof(UserAdministration.Program).Assembly,
    "UserAdministration.wwwroot"
);
app.UseStaticFiles(new StaticFileOptions{FileProvider = embeddedFileProvider });

这将告诉它从哪里获取静态文件。这要求静态文件已被吸入程序集中。这可以通过(程序集)csproj 文件中的以下条目来完成:

<ItemGroup>
   <EmbeddedResource Include="wwwroot/**" />
</ItemGroup>

同样,您必须将以下内容添加到 ConfigureServices 函数中,以便它知道在哪里查找视图文件:

services.Configure<Microsoft.AspNetCore.Mvc.Razor.RazorViewEngineOptions>(options =>
{
    options.FileProviders.Add(new Microsoft.Extensions.FileProviders.EmbeddedFileProvider(typeof(UserAdministration.Program).Assembly));
});

同样,这需要将视图文件吸入程序集:

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

连同原来的加法:

services.AddMvc().AddApplicationPart(assembly).AddControllersAsServices();

...它似乎正在工作。

【讨论】:

    猜你喜欢
    • 2020-02-28
    • 2016-10-10
    • 2020-11-01
    • 1970-01-01
    • 2020-12-02
    • 2016-04-30
    • 2018-01-10
    • 2022-10-25
    相关资源
    最近更新 更多