0
votes

How can I replace custom placeholder before each route in .Net Core 2.1

For Example {serverkey}

[Route("api/{serverkey}/[controller]")]
    [ApiController]
    [AuthorizationFilter]
    public class MonitoringController : Controller
    {
        // Code...
    }

I want each url to be like api/key/Monitoring/Action. So I need to replace key in each request/route.

So basically is there any way to replace the placeholder {serverkey} or something like this {serverkey:key} or even [serverkey] before each request map to this controller.

I know there could be a way like [controller] is replaced automatically by .net core but I am not able to find it.

Thanks in advance.

1
Where is {serverKey} value coming from?Jamie Rees
What do you mean by replaced? Putting a [Route("api/{serverkey}/[controller]")] attribute on top of your controller, and accessing the value in your action methods (like this [HttpGet] public string Get(string serverkey)) isn't enough?Bruno Martins
I have added serverKey in appsetting.json. But i need to find a way to replace route placeholder with this key.Voodoo
@Voodoo What happens is the serverkey provided in the url doesn't match the one in the appsettings file? I think you could deal with that with a custom AuthorizeAttributeBruno Martins
@bmartins I don't want to get the key from input, but I want my route to be replaced by my own key stored.Voodoo

1 Answers

0
votes

I am able to create custom route using IRouteTemplateProvider

public class CustomRouteAttribute : Attribute, IRouteTemplateProvider
    {
        string serverKey = string.Empty;

        public CustomRouteAttribute()
        {
            string serverKey = "Your Key";
        }

        public string Template => $"api/{serverKey}/[controller]";

        public int? Order { get; set; }

        public string Name { get; set; }
    }

It will prepend your key before each route.

Usage: Use this as a attribute on your controller

//[Route("api/[controller]")]
    [CustomRoute]
    [ApiController]
    public class DemoController : ControllerBase
    {}

For Example:

http://localhost:52264/api/Controller/Action will becomes http://localhost:52264/api/Yourkey/Controller/Action