Spooks Spooks - 2 months ago 9
C# Question

Adding a flag to Route Attribute (to enable/disable)

I am looking to add a flag to my Route attribute. I have a flag set in other places for the new feature, but unsure how to add it.

[Route("manage/articles")]
public ActionResult Articles(Model model){ ... }

Answer

Well, you haven't actually given much information about what you're trying to achieve, and as a result, this may be very much an XY problem. But generally speaking, there's no way to disable a route at runtime. It's either going to be an available route or it's not. If this is just some new feature you're working on and you don't want it to be available at all, the best thing I could recommend is simply commenting out the route:

 //Route("manage/articles")]

However, that's not actually the "best thing" in reality. First, unless you've disabled the default route in RouteConfig.cs, you can still get to the action via the traditional /Controller/Action path, so you're not really disabling anything. Second, in truth, you should not be putting any code in production that's not ready to be live to the world, in the first place. If you're working on a new feature, do that in a branch, and don't merge the code in until it's ready to go live. Then, you have no issues.

If this is some situation where you're beta testing or something, and it should be available to some users, but not the world as a whole. You can either rely on Authorize and create a role to assign users into who are allowed to access it, or do some kind of custom authorization in the action or in a custom action filter.