.Net core 3.1 简单视图返回内部服务器错误 500

.Net core 3.1 Simple View returning internal server error 500

最近我问了一个 about exposing a console app through a web browser. I received a very helpful answer and followed the instructions in the link 提供的,但是我似乎无法显示一个简单的视图,即使返回 OK 也能正常工作:

Program.cs

class Program
{
    static void Main(string[] args)
    {
        var host = new WebHostBuilder()
        .UseKestrel()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseStartup<Startup>()
        .Build();

        host.Run();
    }
}

Startup.cs

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseMvc();
    }
}

Controller.cs

public class HomeController : Controller
{
    [Route("home/Index")]
    public IActionResult Index()
    {
        //return Ok("Hello from a controller");   //THIS WORKS 

        IndexModel data = new IndexModel();         //THIS RETURNS INTERNAL SERVER ERROR 500
        data.Title = "THIS";
        data.Message = "MESSAGE";
        return View(data);
    }
}

型号和索引:

public class IndexModel
{
    public string Title { get; set; }
    public string Message { get; set; }
}

@page
@model ConsoleApp1.Views.Home.IndexModel
@{
}
<div>
    <p>@Model.Title</p>
    <p>@Model.Message</p>
</div>

这是我在尝试显示视图时遇到的错误

乍一看,我没有看到默认路由配置

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

我的建议是添加自定义异常中间件

app.UseMiddleware<ExceptionMiddleware>();

和自定义异常处理程序

 public class ExceptionMiddleware
{
    private readonly RequestDelegate next;

    public ExceptionMiddleware(RequestDelegate next)
    {
        this.next = next;
    }

    public async Task InvokeAsync(HttpContext httpContext)
    {
        try
        {
            await next(httpContext);
        }
        catch (Exception ex)
        {
            //inspect the exception here
        }
    }

然后调试并检查在提交请求后您收到的异常的位置和类型。

请注意,您正在创建一个 asp.net-core-3.1 mvc 项目。

您的项目结构应如下所示:

然后将您的 Startup 更改为:

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

    public void Configure(IApplicationBuilder app)
    {
        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

然后在你的 project.csproj. 中将其更改为(注意它是 Sdk="Microsoft.NET.Sdk.Web"):

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

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <PreserveCompilationContext />
  </PropertyGroup>

    <ItemGroup>
        <FrameworkReference Include="Microsoft.AspNetCore.App" />
    </ItemGroup>
</Project>