Alex Rivera | Logout

Nancy Self Host blank response with Razor view

Asked 2011-07-14T23:04:56.540
16

Resolved in Nancy 0.6


I'm trying to get self-hosted Nancy to return a razor view and I can't get it to work. The sample in the Nancy source code uses a web project, but the page they have doesn't say this is required. I've tried specifying the config sections but again they say "This step is totally optional" (italics are theirs). Tracing through the source it doesn't look like razor is a valid view engine, but I don't see where I can add it either in the config or in my own NancyModule... Any help would be appreciated.

View Engines

When I finally figured out they were looking in the views folder, it seems that the cshtml is a supported extension, but the DefaultViewFactory doesn't have it associated with a view engine so I get null:

enter image description here

My code:

public Module1()
{
    Get["/me"] = parms =>
    {
        return View["Static.html"]; // WORKS!
    };
    Get["/you"] = parms =>
    {
        dynamic model = new ExpandoObject();
        //return View["~/Static.cshtml", model];
        //return View["/Static.cshtml", model];
        return View["Static.cshtml", model]; // blank page, no error or anything
    };
}

Static.cshtml is just an html page that says "Hello, world!"

Edit
Report

1 Answer

3

I figured out one part of my problem, the razor assembly wasn't loaded into my AppDomain when I created my NancyHost. NancyHost has TinyIoc scan and create a list of all classes in all loaded assemblies when it starts, and this list never gets udpated. I fixed it by creating a RazorViewEngine to force the assembly to load. Using the Register() call works also, but I think only because it forces the assembly to load, I think Nancy has their own container. All of these locations works, but it still does not work if I put it in my NancyModule:

//TinyIoC.TinyIoCContainer.Current.Register<RazorViewEngine>(); // WORKS
//RazorViewEngine rve = new RazorViewEngine(); // WORKS
m_Host = new NancyHost(m_Uri);
//TinyIoC.TinyIoCContainer.Current.Register<RazorViewEngine>(); // WORKS
m_Host.Start();
TinyIoC.TinyIoCContainer.Current.Register<RazorViewEngine>(); // WORKS

If someone wants to re-write this answer and figure out a cleaner way or a better solution, I'll accept the answer.

answered 2011-07-15T01:31:34.033

Your Answer