从ASP.NET核心中的类库加载和注册API控制器

时间:2016-11-08 16:26:22

标签: c# asp.net-mvc asp.net-core asp.net-core-mvc asp.net-core-webapi

我正在使用ASP.NET Core 1.0.1。我有以下

  • 使用 "Microsoft.AspNetCore.Mvc": "1.0.1" 开发控制器的类库:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace CoreAPIsLibrary.Controllers
{

    [Route("api/[controller]")]
    public class ValuesContoller : Controller
    { 
        public string Get()
        {
            return "value";
        }

        // GET api/values/5
        [HttpGet("{id}")]
        public string Get(int id)
        {
            return "value";
        }

        // POST api/values
        [HttpPost]
        public void Post([FromBody]string value)
        {
        }

        // PUT api/values/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody]string value)
        {
        }
    }
}

这是我的类libray的project.json:

{
  "version": "1.0.0-*",

  "dependencies": {
    "Microsoft.AspNetCore.Mvc": "1.0.1",
    "NETStandard.Library": "1.6.0"
  },

  "frameworks": {
    "netstandard1.6": {
      "imports": "dnxcore50"
    }
  }
}
  • 将托管我的控制器和参考的Asp.net核心应用程序(Web API模板) 那个类库。然而,它永远不会达到突破点 控制器。这是我在Web应用程序中的启动类:

  using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Reflection;
using CoreAPIsLibrary.Controllers;

namespace APIsHost
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc()
              .AddApplicationPart(typeof(ValuesContoller).GetTypeInfo().Assembly).AddControllersAsServices();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseMvc(routes =>
            {
                routes.MapRoute("default", "{controller}/{action}/{id}");
            });
            //app.UseMvc();
        }
    }
}

我还检查了控制器是否被注入:

enter image description here

那么,缺少什么?

4 个答案:

答案 0 :(得分:9)

也许你做错了什么。所以,这是使这项工作的步骤。

  • 创建一个新项目:ASP.NET Core Web Application(.NET Core);
  • 选择Web API模板;
  • 运行项目并访问" api / values"确保它正常工作;
  • 将新项目添加到名为ClassLibrary的解决方案:类库(.NET Core);
  • 删除Class1.cs并创建TestController.cs类;
  • 在ClassLibrary项目的project.json中添加MVC依赖项:

    "dependencies": {
      "NETStandard.Library": "1.6.0",
      "Microsoft.AspNetCore.Mvc": "1.0.0"
    },
    
  • 将TestController.cs更新为:

    [Route("api/[controller]")]
    public class TestController : Controller{
      [HttpGet]
      public IEnumerable<string> Get() {
        return new string[] { "test1", "test2" };
      }
    }
    
  • 在WebAPI项目中添加对ClassLibrary的引用:右键单击&#34;引用&#34; - &gt;&#34;添加引用...&#34;或者像这样更新你的project.json:

    "dependencies": {
      "Microsoft.NETCore.App": {
        "version": "1.0.0",
        "type": "platform"
      },
      "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.Logging": "1.0.0",
      "Microsoft.Extensions.Logging.Console": "1.0.0",
      "Microsoft.Extensions.Logging.Debug": "1.0.0",
      "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
      "ClassLibrary": "1.0.0-*"
    },
    
  • 更新您的Startup.cs ConfigureServices方法:

    public void ConfigureServices(IServiceCollection services) {
      services.AddMvc().AddApplicationPart(Assembly.Load(new AssemblyName("ClassLibrary")));
    }
    
  • 再次运行项目并访问&#34; api / test&#34;;

答案 1 :(得分:5)

您不需要在主Web应用程序的Startup.cs中做任何特殊操作,只需要引用类库。

一个技巧是,要发现您的控制器,您的类库必须直接在其project.json文件依赖项部分中引用MVC:

"Microsoft.AspNetCore.Mvc": "1.0.*"

更新:对于MVC应用程序,我在启动时不需要任何特殊功能,但在我的一个api应用程序中,我确实需要它,因为使用属性路由。

services.AddMvc()
            .AddApplicationPart(Assembly.Load(new AssemblyName("CSharp.WebLib")))
            ;

其中CSharp.WebLib是我的类库的名称

答案 2 :(得分:0)

https://curia.me/how-to-use-a-controller-from-another-assembly-in-asp-net-core/

因此,这是加载控制器而不是整个程序集的更精确的方法。

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    ...

    services.AddMvc()
        .AddApplicationPart(typeof(Namespace.SubNamespace.ControllerName).Assembly);

    ...
}

答案 3 :(得分:-1)

@Fabricio Koch

如果我在dotnet 5中发布了启用修整选项,它将如何在以下代码上工作?

public void ConfigureServices(IServiceCollection services) {
  services.AddMvc().AddApplicationPart(Assembly.Load(new AssemblyName("ClassLibrary")));
}