Jas C.
Jas C.

Reputation: 141

Using regex on MVC routes for controller action to allow only calls that don't contain a given word

I have the following actions defined for two seperate controllers -

Controller A -

[HttpPost]
[Route("~/{configurationId:int}/device/")]
public ActionResult AddDevice() 

Controller B -

[HttpPut]
[Route("~/{configurationId:int}/{fieldname:string}/")]
public ActionResult EditConfiguration()

I need to leave the routes defined as is due to design considerations, etc. I am trying to add a regular expression to Controller B action to exclude the word 'device' for fieldname so that the routes don't 'collide'. This is what I have and it seems to work in regex testing tool.

[HttpPut]
[Route("~/{configurationId:int}/{fieldName:regex(^\b([a-z0-9-]+)\b(?<!device)$)}/")]
public ActionResult EditConfiguration() 

If I call it with this route it says it cannot find the resource. Any ideas/suggestions on how to alter my regex so this will work? -

configuration/3/lock-timeout/

Upvotes: 0

Views: 5492

Answers (1)

Jas C.
Jas C.

Reputation: 141

I ended up figuring this out. Turns out my regex was too complicated. Here is the working expression for anyone looking to put a route constraint to exclude a given word (in my case 'device':

[Route("~/{configurationId:int}/{fieldName:regex(^(?!.*device).*$)}/")]

Upvotes: 3

Related Questions