Use Razor without Microsoft.NET.Sdk.Web

Viewed 5758

I am writing simple consoleApp (netcoreapp2.0)

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

and want to run webserver with mvc.

class Program
{
    static void Main(string[] args)
    {
        WebHost.CreateDefaultBuilder()
            .ConfigureServices(services => services.AddMvc())
            .Configure(app => app.UseDeveloperExceptionPage().UseMvcWithDefaultRoute())
            .UseHttpSys().Build().Run();
    }
}

public class HomeController : Controller
{
    [HttpGet] public ActionResult Index() => View("Index");
}

I get an error while GET http//localhost:5000

One or more compilation references are missing. Ensure that your project is referencing 'Microsoft.NET.Sdk.Web' and the 'PreserveCompilationContext' property is not set to false.

Probably reason is in Razor Engine. How can i make it work? What did i miss?

2 Answers

That error message can be caused by a missing @using in your Index.cshtml view file. Try bypassing the index view and just return a string from your controller like this to see if the error message goes away.

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            WebHost.CreateDefaultBuilder()
                .ConfigureServices(services => services.AddMvc())
                .Configure(app => app.UseDeveloperExceptionPage().UseMvcWithDefaultRoute())
                .UseHttpSys().Build().Run();
        }
    }

    public class HomeController : Controller
    {
        [HttpGet] public string Index() => "Hello World!";
    }
}

csproj

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

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore" Version="2.0.0" />
    <PackageReference Include="Microsoft.AspNetCore.Hosting" Version="2.0.0" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.0.0" />
    <PackageReference Include="Microsoft.AspNetCore.Server.HttpSys" Version="2.0.0" />
    <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="2.0.0" />
  </ItemGroup>

</Project>
Related