从ASP.NET Core中的类库加载和注册API控制器 [英] Loading and registering API Controllers From Class Library in ASP.NET core

查看:38
本文介绍了从ASP.NET Core中的类库加载和注册API控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using ASP.NET Core 1.0.1. I have the following

  • 使用 "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:

This is my class libray's 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应用程序中的启动类:
    • Asp.net core application (Web API Template) that will host my controllers and reference that class library. However, It never hits the break point in the controller. Here is my startup class in the web application:
    •   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();
              }
          }
      }

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

      I also checked if the controller was injected:

      那么,缺少了什么?

      推荐答案

      也许您做错了什么.因此,这是完成这项工作的步骤.

      Maybe you're doing something wrong. So, here are the steps to make this work.

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

      • Create a new project: ASP.NET Core Web Application (.NET Core);
      • Choose the Web API template;
      • Run the project and access the "api/values" to make sure it's working;
      • Add a new project to the solution named ClassLibrary: Class Library (.NET Core);
      • Delete the Class1.cs and create a TestController.cs class;
      • Add the MVC dependency in the project.json from the ClassLibrary project:

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

    • 将您的TestController.cs更新为:

    • Update your TestController.cs to be like this:

      [Route("api/[controller]")]
      public class TestController : Controller{
        [HttpGet]
        public IEnumerable<string> Get() {
          return new string[] { "test1", "test2" };
        }
      }
      

    • 在您的WebAPI项目中添加对ClassLibrary的引用:右键单击引用"->添加引用...",或像这样更新您的project.json:

    • Add the reference to ClassLibrary in your WebAPI Project: right-click on "References"->"Add Reference..." or update your project.json like this:

      "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")));
      }
      

    • 再次运行项目并访问"api/test";
    • 这篇关于从ASP.NET Core中的类库加载和注册API控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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