Self Hosted ASP.NET Core: TagHelper doesn't work

Robert Meyer 29 Sep 2017 .NET Core ASP.NET Core SelfHosted Website TagHelper permalink

I have implemented a simple TagHelper in a ASP.NET Core 2.0 Website, which replace the <time> Tag with the current time. The website never runs in an ISS or Kestrel server, but is hosted by HttpSys in a console / service.

My custom TimeTagHelper:

[HtmlTargetElement("time")]
public class TimeTagHelper : TagHelper
{
    public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
    {
        output.Content.SetHtmlContent($"<h1>{DateTime.Now.ToShortTimeString()}</h1>");
    }
}

If I start the website project directly, the TagHelper works without problems. Launched from the Console / Service, the <time> tag was not replaced. Obviously the _ViewImports.cshtml is not loaded.

The solution: PreserveCompilationContext

These are the steps that helped me:

  1. Add the following ItemGroup definition to my Selhosted.Website.csproj
<ItemGroup>
  <EmbeddedResource Include="wwwroot\**\*;Views\**\*;Areas\**\Views" />
</ItemGroup>
  1. Add the PreserveCompilationContext property to the PropertyGroup in Selhosted.Website.csproj
<PropertyGroup>
  <TargetFramework>netcoreapp2.0</TargetFramework>
  <AssemblyName>SelfHosted.Website</AssemblyName>
  <RootNamespace>SelfHosted.Website</RootNamespace>
  <TypeScriptToolsVersion>2.3</TypeScriptToolsVersion>
  <PreserveCompilationContext>true</PreserveCompilationContext>
</PropertyGroup>
  1. Include the generated SelfHosted.Website.deps.json from the websites bin folder to the SelfHosted.Console project and set the Copy to Output Directory to Copy always.

project properties

You can find the sample project in my GitHub Repo:  roeb/DotNetCoreSamples