1

I'm creating multi-tenancy application, with single database per library, for example.

I want to dynamically add library name to route, for example, when user trying to get all books /Books/GetAllBooks, I must add library name, which could be retrieved from database, for example: /LibraryName/Books/GetAllBooks, so the user can get all books only from the library, which he belongs to.

What should I do? Implement my own IRouter, my own template route, something else?

Yurii N.
  • 5,455
  • 12
  • 42
  • 66

1 Answers1

2

Easy path:

Add id to your url. Look at url of this question:

https://stackoverflow.com/questions/36718499/dynamically-add-route-value-parameter-from-database-in-asp-net-core

You can change last path segment to anything:
https://stackoverflow.com/questions/36718499/foo-bar still bring you here.

Without id:

Implement IRouter. You will need to implement two methods:

1) async Task RouteAsync(RouteContext context) which parse incoming request and add correct "controller", "action" and "id" values into context.RouteData collection. Later, MVC will use this info to call your controller.

2) VirtualPathData GetVirtualPath(VirtualPathContext context) which builds url (string) for controller+action+id values, provided in context.Values collection.

This can help you:

Community
  • 1
  • 1
Dmitry
  • 16,110
  • 4
  • 61
  • 73
  • Adding `id` is not the easiest way, because you need to pass it in every your request, which is crazy. – Yurii N. Apr 19 '16 at 14:19
  • And, could I use dependency injection in my custom router? For example add `ApplicationDbContext` to `MyRouter` constructor. – Yurii N. Apr 19 '16 at 14:34
  • AFAIK, `IRouter`s are created on application start. Create and keep single instance on DbContext in not a good idea.... Both `RouteContext` and `VirtualPathContext` have `Context` property, which is familiar `HttpContext`, which have two `IServiceProvider`-s - `ApplicationServices` and `RequestServices` - better to ask them for instance of your DbContext. Even more better - create some caching service that will keep small amount of routing data in memory and re-read it by timer or by request. – Dmitry Apr 20 '16 at 15:01
  • Ok, seems fine that I could get access to every service in application. – Yurii N. Apr 20 '16 at 15:09