我正在编写简单的consoleApp(netcoreapp2.0)
<Project Sdk="Microsoft.NET.Sdk">
并希望用mvc运行webserver.
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"); }
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.
可能的原因是Razor Engine.
我怎样才能使它工作?我错过了什么?
您的Index.cshtml视图文件中缺少@using可能导致该错误消息.尝试绕过索引视图,只需从控制器返回一个字符串,以查看错误消息是否消失.
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>