Recently I asked a question about exposing a console app through a web browser. I received a very helpful answer and followed the instructions in the link provided, but then I can't seem to display a simple view, even when returning OK works fine:
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);
}
}
The Model and index:
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>
Please notice that you are create a asp.net-core-3.1 mvc
project.
Your project structure should look like this:
Then change your Startup
to:
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?}");
});
}
}
Then in your project.csproj
.Change it to(notice that it's 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>