简体   繁体   中英

Nancy serving views from module in separate library

I'm new to Nancy and I'm trying to setup a webapp with each module/controller in separate project. Main project is empty ASP.NET project and uses Nancy.Hosting.Aspnet nuget package.

What is the elegant way to have this kind of setup?

Say I have the following solution structure:

/ModuleA
- ModuleA.csproj
- IndexA.cshtml (Copy to Output Directory = Copy Always)

/MainModule (references ModuleA)
- MainModule.csproj
- Index.cshtml

Currently to serve IndexA view from ModuleA I have to write View["bin/IndexA"] , which seems pretty ugly because it will also require prefixing javascript/css in the same manner.

You need to configure the nancy conventions in the bootstrapper. Here's the nancy docs: https://github.com/NancyFx/Nancy/wiki/View-location-conventions .

Given this solution structure:

/ModuleA
- ModuleA.csproj
- views/IndexA.cshtml (Copy to Output Directory = Copy Always)
- assets/foo.js (Copy to Output Directory = Copy Always)

/MainModule (references ModuleA)
- MainModule.csproj
- Index.cshtml

In the MainModule bootstrapper:

public class Bootstrapper : DefaultNancyBootstrapper
{
    protected override void ConfigureConventions(Nancy.Conventions.NancyConventions nancyConventions)
    {
        base.ConfigureConventions(nancyConventions);

        // for views in referenced projects
        nancyConventions.ViewLocationConventions.Add(
            (viewName, model, context) => string.Concat("bin/views/", viewName));

        // for assets in referenced projects         
        nancyConventions.StaticContentsConventions.Add(
            Nancy.Conventions.StaticContentConventionBuilder.AddDirectory("assets", "bin/assets"));
    }
}

In IndexA.cshtml :

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <script src="/assets/foo.js"></script>
    </head>
    <body></body>
</html>

As mentioned by @eth0 in the comments, you can also use views saves as resources but this is outside the scope of my answer. Here is a good article on the topic: http://colinmackay.scot/2013/05/02/configuring-the-nancy-to-use-views-in-a-separate-assembly/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM