3

I'm using ASP.NET Core. The convention is that the routing system considers a FooController class to be a controller with the name Foo.

I need to override this convention. I want to do something like this:

[ControllerName("Bar")]
public class SomeArbitraryName : Controller {
}

Or like this:

public class SomeArbitraryName : Controller("Bar") {
}

Is that possible somehow?

EDIT: No that linked "duplicate" question is not for ASP.NET Core!

grokky
  • 8,537
  • 20
  • 62
  • 96

2 Answers2

4

Attribute routing still exists in Asp.Net Core

[Route("Bar")]
public class SomeArbitraryName : Controller
{
    // ...
}

See Documentation: Routing to Controller Actions - Attribute Routing

Nkosi
  • 235,767
  • 35
  • 427
  • 472
  • Thanks @haim770 was adding the link when you did it for me. – Nkosi Dec 28 '16 at 11:58
  • Problem here is that if I have an action `[Route("Bar/edit")]public void IActionResult edit(int id)` then it doesn't route correctly... it will in fact route to `Bar` instead of `Bar/edit`... – grokky Dec 28 '16 at 12:01
  • either override the action route `[Route("/Bar/edit")]` or remove bar from the action route so that it inherits the prefix from the controller. – Nkosi Dec 28 '16 at 12:10
1

You could implement your own System.Web.Mvc.IControllerFactory and do ControllerBuilder.Current.SetControllerFactory(new MyImpl()) at some point in the application initialization step

Edit: This advice applies to ASP.NET MVC 5 and Core might have different interfaces for something similar

Adrian Zanescu
  • 7,907
  • 6
  • 35
  • 53
  • The OP is asking about Asp.Net Core. Also, `ControllerBuilder` is responsible for construction of known controllers (after routing is done). That's not what is needed here. – haim770 Dec 28 '16 at 11:52
  • @haim770 seems you are right. i think i need to play a bit with Core :) – Adrian Zanescu Dec 28 '16 at 11:56