14

How to create prefixed routing for MVC CRUD operation. I am working on an application that requires admin and front-end. For the admin I want all route to point to localhost:5000/admin/....

I have different Controllers

public class RoomsController : Controller
{
    // GET: Rooms        
    public async Task<IActionResult> Index()
    {

        return View(await _context.Rooms.ToListAsync());
    }

    //...
}

and

public class SlidersController : Controller
{
    private readonly ApplicationDbContext _context;

    public SlidersController(ApplicationDbContext context)
    {
        _context = context;
    }

    // GET: Sliders
    public async Task<IActionResult> Index()
    {
        return View(await _context.Sliders.ToListAsync());
    }

    //...
}

Now I want the admin route to be

localhost:5000/admin/rooms
localhost:5000/admin/slider

while other routes remain

localhost:5000/
localhost:5000/about
localhost:5000/...
Nkosi
  • 235,767
  • 35
  • 427
  • 472
rilly009
  • 253
  • 2
  • 4
  • 12
  • Might be worth looking at areas - see [How to use an Area in ASP.NET Core](https://stackoverflow.com/questions/36535511/how-to-use-an-area-in-asp-net-core#36535512) – SpruceMoose Dec 21 '17 at 11:41
  • 2
    What exactly is the point of that `admin/` prefix? Does this have any effect on the behavior of your routes? – poke Dec 21 '17 at 12:02
  • I am trying to segment the admin side from the normal client area. So I decided to to for with @CalC option Area – rilly009 Dec 21 '17 at 12:11

2 Answers2

27

You can also use Attribute Routing for this. Till ASP.Net Web API we have the attribute named [RoutePrefix], but in ASP.Net Core 2 we can use [Route] attribute for the same purpose.

[Route("api/[controller]/[action]")]
public class DistrictController : ControllerBase
{

    [Route("{id:int:min(1)}")] // i.e. GET /api/District/GetDetails/10
    public IActionResult GetDetails(int id)
    {
    }

    // i.e. GET /api/District/GetPage/?id=10
    public IActionResult GetPage(int page)
    {
    }

    [HttpDelete]
    [Route("{id:int:min(1)}")] // i.e. Delete /api/District/Delete/10
    public IActionResult Delete(int id)
    {
    }

    [HttpGet]
    [Route("~/api/States/GetAllState")] // i.e. GET /api/States/GetAllState
    public IActionResult GetStates()
    {
    }
}
Nilay Mehta
  • 1,732
  • 2
  • 20
  • 26
  • In my case it was as easy as replacing `RoutePrefix` with `Route`, did not have to change the string value, was picked up by Swagger just fine. I'm converting from .NET 4.5 to Core 6.0. Leaving it here for future visitors. Thanks! – Victor Zakharov Dec 07 '21 at 13:19
0

I solve the Problem by using MVC Area docs

rilly009
  • 253
  • 2
  • 4
  • 12