有没有办法将ASP.NET Core应用程序区域打包为NuGet包?

时间:2016-09-09 21:08:41

标签: asp.net-core nuget asp.net-core-mvc

我正在开发一个ASP.NET Core应用程序,我希望将其作为NuGet包发布,您可以将其添加到任何Core Web项目中。该应用程序实际上完全局限于项目中的一个区域(即/ Areas / MyArea),包括控制器,视图,服务类,模型,视图等,除了少数部分。真的,这些是我喜欢神奇地添加到现有网络应用程序的部分:

  • 区域及其中的所有内容
  • 它的CSS和JS在wwwroot / lib / myapp
  • Startup类中的条目
  • 根目录中的MyApp.json

我知道NuGet会恢复软件包依赖关系,但我不确定如何考虑客户端软件包。

有什么建议吗? NuGet是错误的工具吗?

2 个答案:

答案 0 :(得分:1)

目前尚无法从nuget包中将文件传送到Web应用程序。我认为有一些讨论和工作正在进行中,以便将来做到这一点。

我在项目中处理的方法是嵌入视图和所需的静态js和css资源,这在project.json中是这样完成的:

“buildOptions”:{         “embed”:[“Views / ”,“js / ”,“css / **”]     },

我创建了一个controller to serve my static resources

public class cscsrController : Controller
{  
    private ContentResult GetContentResult(string resourceName, string contentType)
    {
        var assembly = typeof(cscsrController).GetTypeInfo().Assembly;
        var resourceStream = assembly.GetManifestResourceStream(resourceName);
        string payload;
        using (var reader = new StreamReader(resourceStream, Encoding.UTF8))
        {
            payload = reader.ReadToEnd();
        }

        return new ContentResult
        {
            ContentType = contentType,
            Content = payload,
            StatusCode = 200
        };
    }

    [HttpGet]
    [AllowAnonymous]
    public ContentResult bootstrapdatetimepickercss()
    {
        return GetContentResult(
            "cloudscribe.Core.Web.css.bootstrap-datetimepicker.min.css",
            "text/css");
    }

    [HttpGet]
    [AllowAnonymous]
    public ContentResult momentwithlocalesjs()
    {
        return GetContentResult(
            "cloudscribe.Core.Web.js.moment-with-locales.min.js",
            "text/javascript");
    }

}

然后我链接到我需要加载js和/或css的视图中的控制器动作。

为了使嵌入视图有效,我创建了RazorViewEngineOptions的扩展方法:

public static RazorViewEngineOptions AddEmbeddedViewsForCloudscribeCore(this RazorViewEngineOptions options)
{
    options.FileProviders.Add(new EmbeddedFileProvider(
            typeof(SiteManager).GetTypeInfo().Assembly,
            "cloudscribe.Core.Web"
        ));

    return options;
}

并且必须从Web应用程序Startup中的ConfigureServices调用,如下所示:

services.AddMvc()
    .AddRazorOptions(options =>
    {
        options.AddEmbeddedViewsForCloudscribeCore();

    })
    ;

这种技术在区域应该是一样的。请注意,一个很酷的事情是用户可以下载视图并在本地安装它们,这将覆盖嵌入视图的使用,从而可以轻松自定义部分或全部视图。通过覆盖视图,还可以根据需要在本地手动安装js和css,如果需要自定义,则更改视图以链接到这些本地文件。最终的结果是我的nuget拥有它需要的一切,所以只有一些启动配置才能让事情发挥作用。

答案 1 :(得分:0)

几年后,通过使用Razor类库,可以在ASP.NET Core> v2.x中实现这一点。

相关问题