ASP.NET Core MVC controllers in separate assembly

穿精又带淫゛_ 提交于 2019-11-26 16:39:11

问题


I'm using ASP.NET MVC Core RC-2. I have a web project targeting the full .NET framework. I also have a separate class library in the solution, also targeting the full framework.

In the class library, I have a controller, marked with a route attribute. I have referenced the class library from the web project. This assembly references the nuget package Microsoft.AspNetCore.Mvc v. 1.0.0-rc2-final.

It was my understanding that this external controller would be discovered automatically, e.g. http://www.strathweb.com/2015/04/asp-net-mvc-6-discovers-controllers/

However this doesn't work for me- I browse to the URL of the route and I get a blank page and it doesn't hit my controller breakpoint.

Any ideas how to get this working?

Interestingly, it does seem to work for web projects targeting .NET Core Framework, referencing a class library also targeting .NET Core. But not for a web project targeting the full framework, referencing a standard .NET class library.

Note: this is MVC Core which is supposed to support this kind of scenario without any MVC<=4 routing overrides.


回答1:


I believe you are hitting the following known issue in RC2. https://github.com/aspnet/Mvc/issues/4674 (workaround is mentioned in the bug)

This has been fixed since then but will only be available in next release (unless you are ok with using nightly builds)




回答2:


Still an issue in ASP.Net Core 1.0, not sure if it's by design now. Easiest solution is to do this in Startup.cs/ConfigureServices

services.AddMvc()
  .AddApplicationPart(typeof(<class in external assembly>).Assembly)
  .AddControllersAsServices();

AddApplicationPart explicitly includes the assembly in searches for controllers. The call to AddControllersAsServices() will add all the discovered controllers into the services collection, and if you put a breakpoint after this line and inspect 'services', you will see in the collection all the controller types which have been found.

You might also want to check here: https://docs.asp.net/en/latest/migration/rc1-to-rtm.html#asp-net-5-mvc-compile-views as the discovery rules are now changed for controllers from RC1.

Also remember to use IActionResult instead of ActionResult!



来源:https://stackoverflow.com/questions/37725934/asp-net-core-mvc-controllers-in-separate-assembly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!