How to add Razor support to existing Windows Service host

Hi all,

I’ve been using ServiceStack for a few years now but I’m a bit of a noob with ServiceStack.Razor.

I have a Windows Service that contains host a ServiceStack service as well as running some background tasks. My ServiceStack web API controls the background tasks, pausing, restarting (just the task, not the windows service) etc…

I’d like to add a web page to interface with my web API but I’m not sure where to start.

Apart from the references and adding the Razor plugin what else do I need to do?

  • Add a View folder with Shared sub folder? And add my cshtml files
  • Create a web.config? Or will my app.config suffice?
  • How does Razor know to retrieve views from which folder…?

I’ve read some of the documentation but it appears to be more geared to starting with a Razor project and I’m not sure what I need to do to add it to an existing project.

Any help appreciated…

For self-hosting projects you’d need the Razor Config in both the Web.config and App.config your App looks at App.config whilst VS.NET looks at Web.config for its intelli-sense (VS.NET Razor intelli-sense for self-hosting Apps is greatly improved in .NET Core). You can get the Web.config from the docs or you could create a ServiceStack Self Host with Razor project in ServiceStackVS and copy it from there.

If you just want a Razor page you can just have a single default.cshtml Content Page, you don’t need anything else.

If you want to extract the Layout from the razor page you can then extract the template from your default.cshtml and add it to Views/Shared/_Layout.cshtml, e.g:

<!DOCTYPE html>
<html lang="en-us">
    <title>ServiceStack Self Host with Razor</title>
    <h1 class="navbar">ServiceStack Self Host with Razor</h1>
    <div id="content">

Which will render the content left in default.cshtml in @RenderBody().

Unfortunately VS.NET doesn’t properly support Razor intelli-sense in non ASP.NET projects (e.g. Console/WinService) so while it will still work, you’ll still get VS.NET designer warnings.

    ViewBag.Title = "ServiceStack Self Host with Razor";

<h2>Hello World Service</h2>

<form action="@(new Hello().ToPostUrl())">
        <input class="form-control input-lg" name="Name" type="text" placeholder="Type your name">

Thanks @mythz.

I’ve managed to get a view page working correctly but my default.cshtml (in the root of may app) won’t load on navigating to the web root url. It redirects to /metadata.

Any ideas?

You’d need to either set the Build Action of each Razor View to Content and Copy to output directory to Copy if newer so it’s copied to the bin/ directory or you could change the physical path ServiceStack looks at to the project folder with:

            SetConfig(new HostConfig
                DebugMode = true,
                WebHostPhysicalPath = Path.GetFullPath(Path.Combine("~".MapServerPath(), "..", "..")),

Doh - I’d done that for the View pages as well!

Thanks again!

1 Like