在没有.NET Core SDK的情况下将ASP.NET Core MVC作为控制台应用程序项目运行 [英] Running ASP.NET Core MVC as a Console Application Project without .NET Core SDK

查看:101
本文介绍了在没有.NET Core SDK的情况下将ASP.NET Core MVC作为控制台应用程序项目运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题背景

我正在创建一个工具,可以生成MVC解决方案(* .sln)并使用msbuild构建它们,以便可以对其进行部署.该工具需要.NET Framework 4.5.2.

I'm creating a tool, tha generates MVC solutions(*.sln) and building(with msbuild) them so they could be deployed. Tool requires .NET Framework 4.5.2.

现在,我想生成ASP.NET Core MVC应用程序.这样的应用程序可以在4.5.X下运行,但是我不确定msbuild是否可以处理project.json(因此我正在使用packages.config),并且我无法安装.NET Core,因为每个教程都指出这是开发ASP.NET的先决条件.核.目前,我正计划在Windows上部署生成的应用程序.

Now I want to generate ASP.NET Core MVC application. Such applications could be run under 4.5.X, but I'm unsure if msbuild could handle project.json(so i'm using packages.config) and I cannot install .NET Core as every tutorial indicate as prerequisite for developing ASP.NET Core. Currently I'm planning to deploy generated applications on Windows.

问题:

因此,我创建了一个简单的控制台应用程序,而不是.NET Core项目: 在那里,我已经安装了所有需要的软件包,例如:

So instead of .NET Core project I've created a simple console application: There I've installed there all packages needed, like:

  <package id="Microsoft.AspNetCore.Mvc" version="1.0.1" targetFramework="net452" />

然后使用Kestrel自托管应用程序:

And SelfHosted the application using Kestrel:

    public class Program {
    static void Main() {
        var host = new WebHostBuilder()
            .UseKestrel()
            .UseIISIntegration()
            .UseStartup<Startup>()
            .Build();

        host.Run();
    }
}

我添加了带有View的Controller.当我发出请求时,控制器被命中,但是View无法在运行时进行编译:

I've added Controller with a View. When I do a request, controller is hit, but View cannot be compiled in runtime:

此行为是否与我正在使用控制台应用程序而不是 ASP.NET Core Web应用程序有关?是否可以将功能齐全的MVC应用程序创建为简单的控制台应用程序?

Is this behavior related to the fact I'm using Console Application and not ASP.NET Core Web Application? Is it possible to create a full-featured MVC application as a simple console application?

更新:

我认为我已经找到了一种解决方法,灵感来自阅读github 问题:

I think I've found a workaround inspired from reading github issues:

 public void ConfigureServices(IServiceCollection services) {
        services.AddMvc()
                .AddRazorOptions(options => {
                                     var previous = options.CompilationCallback;
                                     options.CompilationCallback = context => {
                                                                       previous?.Invoke(context);
                                                                       var refs = AppDomain.CurrentDomain.GetAssemblies()
                                                                                           .Where(x => !x.IsDynamic)
                                                                                           .Select(x => MetadataReference.CreateFromFile(x.Location))
                                                                                           .ToList();
                                                                       context.Compilation = context.Compilation.AddReferences(refs);
                                                                   };
                                 });
    }

这似乎使Razor呈现了我的观点.但是我不确定是否可以接受它作为解决方案.

That seems to make Razor to render my view. But I'm not sure yet if it can be accepted as a solution.

推荐答案

目前,无法使用MSBuild来构建.NET Core应用.但是可以创建一个控制台应用程序(不是.Net Core)并使用Nuget添加相同的程序包(逐步介绍).

Right now it's not possible to build a .NET Core app using MSBuild. But it's possible to create a Console application (not .Net Core) and add the same packages using Nuget (step-by-step bellow).

根据此路线图 ,这将在不久的将来成为可能.

According to this road map, it will be possible in the near future.

上面链接中的信息:

2016年第四季度/2017年第一季度

Q4 2016 / Q1 2017

这将是第一个次要更新,主要着眼于将.xproj/project.json替换为.csproj/MSBuild.项目格式更新应该是自动的.只需打开1.0项目,它就会更新为新的项目格式.在运行时和库中还将有新功能和改进.*

This will be the first minor update, mainly focused on replacing .xproj/project.json with .csproj/MSBuild. Project format update should be automatic. Just opening a 1.0 project will update it to the new project format. There will also be new functionality and improvements in the runtime and libraries.*

编辑(使用kestrel创建控制台应用程序的步骤):

EDIT (steps to create a console app with kestrel):

我创建了一个控制台应用程序(不是.NET Core控制台),并且能够使用简单的MVC API运行kestrel.

I created a Console Application (not .NET Core console) and I was able to run kestrel with a simple MVC API.

这就是我所做的:

  • 我看到了在现有.net核心应用程序中使用的依赖项,然后,我将它们添加为nuget引用:

  • I saw the dependencies I use in a existing .net core app, then, I added they as a nuget reference:

"Microsoft.AspNetCore.Mvc": "1.0.0",
"Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
"Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
"Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
"Microsoft.Extensions.Configuration.FileExtensions": "1.0.0",
"Microsoft.Extensions.Configuration.Json": "1.0.0",
"Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0"

  • 修改了主要方法:

  • Modified the main method:

    static void Main(string[] args) {
      var host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .Build();
      host.Run();
    }
    

  • 创建了一个Startup.cs(使用问题中提供的解决方法进行了更新):

  • Created a Startup.cs (UPDATED with the workaround provided in the question):

      public class Startup {
        public Startup(IHostingEnvironment env) {
          var builder = new ConfigurationBuilder()
              .SetBasePath(env.ContentRootPath)
              .AddEnvironmentVariables();
          Configuration = builder.Build();
        }
    
        private IHostingEnvironment CurrentEnvironment { get; set; }
        private IConfigurationRoot Configuration { get; }
    
        public void ConfigureServices(IServiceCollection services) {
                services.AddMvc().AddRazorOptions(options => {
                 var previous = options.CompilationCallback;
                 options.CompilationCallback = context => {
                   previous?.Invoke(context);
                   var refs = AppDomain.CurrentDomain.GetAssemblies()
                          .Where(x => !x.IsDynamic)
                          .Select(x => MetadataReference.CreateFromFile(x.Location))
                          .ToList();
                 context.Compilation = context.Compilation.AddReferences(refs);
                };
              });
        }
    
        public void Configure(IApplicationBuilder app) {
          app.UseStaticFiles();
    
          app.UseMvc(routes => {
            routes.MapRoute(
              name: "default",
              template: "{controller=Home}/{action=Index}/{id?}");
          });
        }
      }
    

  • 添加一个类作为我的MVC控制器:

  • Add a class to be my MVC Controller:

      [Route("api/[controller]")]
      public class ValuesController : Controller {
    
        // GET api/values
        [HttpGet]
        public IEnumerable<string> Get() {
          return new string[] { "value1", "value2" };
        }
    

  • 由于出现错误,我不得不将libuv.dll手动复制到bin文件夹中.

  • I had to copy mannualy the libuv.dll to the bin folder because I was getting an error.

    通过这些步骤,我能够运行控制台应用程序. 在下面的图像中,您可以看到我的项目结构和运行的茶est:

    With these steps I was able to run my console application. In the image bellow you can see my project structure and the kestrel running:

    这篇关于在没有.NET Core SDK的情况下将ASP.NET Core MVC作为控制台应用程序项目运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    相关文章
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆