Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core MVC controllers in separate assembly

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.

like image 646
booler Avatar asked Jun 09 '16 12:06

booler


People also ask

Can you mix razor pages and MVC?

You can add support for Pages to any ASP.NET Core MVC app by simply adding a Pages folder and adding Razor Pages files to this folder. Razor Pages use the folder structure as a convention for routing requests.

Can a controller have multiple models?

Now, question arises, can you use multiple models in 1 controller? Answer: Yes.


1 Answers

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!

like image 115
James Ellis-Jones Avatar answered Sep 19 '22 19:09

James Ellis-Jones