简体   繁体   中英

Asp.Net Core - Configurable attribute route for web service

How do I set configurable for api text below. So, user can change it to any name from the appsettings.json file. Or, can I set a default text to put in the link, so any link will have this text.

[Route(" api /[controller]")]

var config = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json").Build();

// [Route("config["ApiName"]/[controller]")]
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    // GET api/values
    [HttpGet]
    public ActionResult<IEnumerable<string>> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/values/5
    [HttpGet("{id}")]
    public ActionResult<string> Get(int id)
    {
        return "value";
    }
}

The ASP.NET Core RouteAttribute doesn't do much itself. You can try inheriting it and reading the your configuration inside. There's more then 1 RouteAttribute classes in .NET Core, so make sure you are inheriting the same one you used in your example.

It would look something like this:

public class MyDynamicRouteAttribute : RouteAttribute
{
    public MyDynamicRouteAttribute(string template) : super(FillTemplate(template)) {}

    private static string FillTemplate(string template)
    {
        var config = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json").Build();

        return template.Replace(<do what you need to do>);
    }
}

Then you would use it as you described:

[MyDynamicRoute("{ApiName}/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    ...
}

Notice that FillTemplate() is declared static . As the class hasn't been instantiated yet, you cannot call an instance method.

I haven't tested to see how it runs, but this should get you started.

As a side note, you should probably investigate if this opens any security holes.


Off topic, there's probably a better way to retrieve the configuration through Dependency Injection , but I've used the code you provided.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM