繁体   English   中英

ASP.NET Core MVC主项目无法在单独的程序集中到达Controllers

[英]ASP.NET Core MVC main project can't reach Controllers in separate assembly

我想使用一个单独的项目来存储我的测试应用程序的控制器。 由于ASP.NET Core的工作原理,您需要调用services.AddMvc().AddApplicationPart以及要添加的程序集。

我使用Visual Studio 2017 (所以没有更多的project.json

问题是我无法到达我想要包含的程序集!

我在我的项目中添加了参考:

在此输入图像描述

另外,我决定像AppDomian一样使用polyfill(为了达到我需要的程序集):

 public class AppDomain
    {
        public static AppDomain CurrentDomain { get; private set; }

        static AppDomain()
        {
            CurrentDomain = new AppDomain();
        }

        public Assembly[] GetAssemblies()
        {
            var assemblies = new List<Assembly>();
            var dependencies = DependencyContext.Default.RuntimeLibraries;
            foreach (var library in dependencies)
            {
                if (IsCandidateCompilationLibrary(library))
                {
                    var assembly = Assembly.Load(new AssemblyName(library.Name));
                    assemblies.Add(assembly);
                }
            }
            return assemblies.ToArray();
        }

        private static bool IsCandidateCompilationLibrary(RuntimeLibrary compilationLibrary)
        {
            return compilationLibrary.Name == ("TrainDiary")
                || compilationLibrary.Dependencies.Any(d => d.Name.StartsWith("TrainDiary"));
        }
    }

但是当我使用它时,列表中只有一个程序集(仅与该项目本身相关联,而不是与控制器相关联)。

这是我的Startup.cs

public class Startup
    {

        public IConfigurationRoot Configuration { get; }
        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();
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            var assemblies = GetAssemblies(); // I tought I will find there Assmbly I need but no

            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddReact();
            services.AddMvc();
            services.AddLogging();
        }

        // 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();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseReact(config =>
            {
            });

            app.UseStaticFiles();
            app.UseMvcWithDefaultRoute();
        }

        public List<Assembly> GetAssemblies()
        {
            Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
            List<Assembly> currentAssemblies = new List<Assembly>();

            foreach (Assembly assembly in assemblies)
            {
                if (assembly.GetName().Name.Contains("TrainDiary"))
                {
                    currentAssemblies.Add(assembly);
                }
            }

            return currentAssemblies;
        }

    }

如何让我的项目也在另一个项目中查找控制器? 为什么不能看到它?

UPD

试图直接在这里做这个例子

所以我的代码开始看起来像这样:

var controllersAssembly = Assembly.Load(new AssemblyName("TrainDiary.Controllers")); 
services.AddMvc()
        .AddApplicationPart(controllersAssembly)
        .AddControllersAsServices();

它成功获得组装:

在此输入图像描述

但是当我尝试调用Controller函数时 - 它失败了!

控制器代码:

[Route("Login")]
    public class LoginController: Controller
    {
        [Route("Login/Test")]
        public void Test(string name, string password)
        {
            string username = name;
            string pass = password;
        }
    }

要求:

在此输入图像描述

UPD2

出于某种原因,删除Routes帮助:

public class LoginController: Controller
    {
        public void Test(string name, string password)
        {
            string username = name;
            string pass = password;
        }
    }

在此输入图像描述

所以,如果总结一下:

1)您需要使用控制器向您的单独项目Add Reference

2)配置服务(部分):

public void ConfigureServices(IServiceCollection services)
{
  var controllersAssembly = Assembly.Load(newAssemblyName("SomeProject.MeetTheControllers"));

  services.AddMvc().AddApplicationPart(controllersAssembly).AddControllersAsServices();
}

3)我的配置看起来像那样(注意UseMvcWithDefaultRoute ):

   // 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();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseReact(config =>
            {
            });

            app.UseStaticFiles();
            app.UseMvcWithDefaultRoute();
        }

所以在我的控制器这样的情况下你不需要在这里放置Routes属性,只需通过Some/Test url调用它

namespace SomeProject.MeetTheControllers.Test
{
    using Microsoft.AspNetCore.Mvc;

    public class SomeController: Controller
    {
        public void Test(string name, string notname)
        {
            string username = name;
            string nan = notname;
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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