首页 > 解决方案 > 找不到 Index.cshtml NET Core App 3.0

问题描述

是的,对此有很多问题和答案,但我找不到适合我的问题 - 我只是看不到我错过了什么,或者做错了什么。

只需要提供几个 Razor 页面(以及 SignalR)的 Windows 桌面应用程序。如果我使用 HomeController 的 V1 浏览到https://localhost:5000(见下文),那么浏览器会正确显示字符串,所以我知道我正在浏览到正确的 URI。但是,如果我更改控制器以返回视图,我会得到以下信息:

An unhandled exception occurred while processing the request.
InvalidOperationException: The view 'Index' was not found. The following locations were searched:
/Views/Home/Index.cshtml
/Views/Shared/Index.cshtml
/Pages/Shared/Index.cshtml

Microsoft.AspNetCore.Mvc.ViewEngines.ViewEngineResult.EnsureSuccessful(IEnumerable<string> originalLocations)

运行后者时,输出窗口显示:

Microsoft.Hosting.Lifetime: Information: Now listening on: http://localhost:5000
Microsoft.Hosting.Lifetime: Information: Application started. Press Ctrl+C to shut down.
Microsoft.Hosting.Lifetime: Information: Hosting environment: Development
Microsoft.Hosting.Lifetime: Information: Content root path: C:\Users\geoff\source\repos\xxx\yyy\bin\Debug\netcoreapp3.0

Index.cshtml(在那个外壳中)位于(也在 wwwroot\Views 等下):

C:\Users\geoff\source\repos\xxx\yyy\bin\Debug\netcoreapp3.0\Views\Home\Index.cshtml

Index.cshtml 设置为 BuildAction: Content 和 CopyToOutput: CopyIfNewer,是的,当使用正确的大小写运行时,该文件就在那里。

我已经阅读了有关添加视图引擎的内容,但我的理解是 Razor 无论如何都在那里。我认为这是我唯一没有尝试过的事情。我还尝试了自定义路由而不是默认路由,但没有成功。

非常感谢帮助。

.csproj 的一部分:

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

  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>netcoreapp3.0</TargetFramework>
    <UseWPF>true</UseWPF>
    <PreserveCompilationContext />
    <MvcRazorCompileOnPublish>true</MvcRazorCompileOnPublish>
    <MvcRazorExcludeViewFilesFromPublish>false</MvcRazorExcludeViewFilesFromPublish>
    <MvcRazorExcludeRefAssembliesFromPublish>false</MvcRazorExcludeRefAssembliesFromPublish>
  </PropertyGroup>

  <ItemGroup>
    <None Remove="Views\Home\Index.cshtml" />
    <None Remove="wwwroot\Views\Home\Index.cshtml" />
  </ItemGroup>

  <ItemGroup>
    <Content Include="Views\Home\Index.cshtml">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </Content>
  </ItemGroup>

  <ItemGroup>
    <Content Include="wwwroot\Views\Home\Index.cshtml">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </Content>
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.ViewCompilation" Version="1.1.0">
      <PrivateAssets>All</PrivateAssets>
    </PackageReference>
  </ItemGroup>
  <ItemGroup>
    <None Update="wwwroot\**\*;**.cshtml">
      <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
    </None>
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="AvalonEdit" Version="5.0.4" />
    <PackageReference Include="Microsoft.AspNet.WebApi.Core" Version="5.2.7" />
    <PackageReference Include="Microsoft.AspNetCore.App" Version="3.0.0-preview3-19153-02" />
    <PackageReference Include="Microsoft.AspNetCore.Http" Version="2.2.2" />
    <PackageReference Include="Microsoft.AspNetCore.Http.Connections" Version="1.1.0" />
    <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="2.2.0" />
    <PackageReference Include="Microsoft.AspNetCore.JsonPatch" Version="3.0.0-preview5-19227-01" />
    <PackageReference Include="Microsoft.AspNetCore.SignalR" Version="1.1.0" />
    <PackageReference Include="Microsoft.AspNetCore.SignalR.Core" Version="1.1.0" />
    <PackageReference Include="Microsoft.Extensions.Hosting" Version="2.2.0" />
    <PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="2.2.0" />
  </ItemGroup>

</Project>

应用程序.xaml.cs:

public partial class App : Application
{
    private IHost _host;

    protected override void OnStartup(StartupEventArgs e)
    {
        string path = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
        _host = Host.CreateDefaultBuilder(e.Args)
            .UseContentRoot(path)
            .ConfigureWebHostDefaults(webHostBuilder => webHostBuilder.UseStartup<StartUp>())
            .ConfigureServices(services =>
            {
                services.AddTransient<MainWindow>();

                services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
                {
                    builder.AllowAnyOrigin()
                           .AllowAnyMethod()
                           .AllowAnyHeader();
                }));

                services.AddMvc();

                services.AddSignalR().AddHubOptions<SsoHub>(options =>
                {
                    options.EnableDetailedErrors = true;
                });

                services.AddSingleton<ISsoHubHelper, SsoHubHelper>();

            })
            .Build();

        _host.Start();
    }

    protected override void OnExit(ExitEventArgs e) => _host.Dispose();
}

startup.cs 的一部分:

public class StartUp
{
    public static IServiceProvider ServiceProvider { get; private set; }
    public static T GetService<T>() { return ServiceProvider.GetRequiredService<T>(); }

    public static ISsoHubHelper HubContext;

    public void Configure(IApplicationBuilder app, IServiceProvider serviceProvider)
    {
        app.UseCors(builder =>
        {
            builder.AllowAnyOrigin()
                   .AllowAnyMethod()
                   .AllowAnyHeader();
        });

        app.UseStaticFiles();
        app.UseStatusCodePages();
        app.UseDeveloperExceptionPage();
        app.UseMvcWithDefaultRoute();

        app.UseSignalR((configure) =>
        {
            var desiredTransports =
                HttpTransportType.WebSockets |
                HttpTransportType.LongPolling;

            configure.MapHub<SsoHub>("/ssohub", (options) =>
            {
                options.Transports = desiredTransports;
            });
        });

        ServiceProvider = serviceProvider;
        HubContext = GetService<ISsoHubHelper>();
    }
}

HomeController.cs(V1 - 有效):

public class HomeController : Controller
{
    public string Index()
    {
        return "Hello, world!";
    }

}

HomeController.cs(V2 - index.cshtml 未找到):

public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

}

标签: asp.net-corerazorkestrel-http-server

解决方案


找到了。叹。通过一个相当不相关的问答,我使用资源监视器确定甚至没有尝试打开文件。这让我相信这些页面应该已经被编译——这导致了这篇文章,它表明了一个重大的变化。引用其中一个答案(来源:Dmitry Pavlov):

  1. 参考Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation(预发布)
  2. 称呼services.AddMvc().AddRazorRuntimeCompilation()

最后它起作用了。cshtml 文件一直都在那里,它应该是并且知道它是,但它只是没有被编译。


推荐阅读