Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Razor without Microsoft.NET.Sdk.Web

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?

like image 879
Sergey Shuvalov Avatar asked Sep 21 '17 11:09

Sergey Shuvalov


1 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>
like image 195
Padhraic Avatar answered Sep 28 '22 06:09

Padhraic