0

I want to map a WebAPI action method to urls on the format api/v2/l8n/{cultureCode}, but to avoid route collisions with other methods, I need to constrain the cultureCode parameter to only values matching the regex ^\w{2}(?:-\w{2})?$, i.e. sv and en-GB, but not hello.

I have a RoutePrefix attribute on the controller that takes care of api/v2/i8n, so I tried mapping the action with

[Route(@"{cultureString:regex(^\w{2}(?:-\w{2})?$)")]

but then an error was thrown at configuration time stating that {cultureString:regex(^\w{2 was a bad route value. I tried replacing \w{2} with \w\w as well as removing the @ and escaping my backslashes, but was then instead presented with

The route template cannot start with a '/' or '~' character and it cannot contain a '?' character.

If I can't even use ?, how can I ever create a regex with an optional part?

Tomas Aschan
  • 58,548
  • 56
  • 243
  • 402

1 Answers1

1

I do hope there is no such limitation on the pipeline operator or alternation operator, using which and some anchors, you could get it to work.

[Route(@"{cultureString:regex(^\w\w(-\w{2}|)$)}")]

What the above means is that it matches either two \w followed by another two \w or end of the string, $

Tomas Aschan
  • 58,548
  • 56
  • 243
  • 402
Amit Joki
  • 58,320
  • 7
  • 77
  • 95
  • 1
    now it matches `dd-ddd` also. I suggest you to use `^\w\w(-\w{2}|)$` – Avinash Raj Feb 02 '15 at 17:01
  • Could have worked, but unfortunately it didn't: `The inline constraint resolver of type 'DefaultInlineConstraintResolver' was unable to resolve the following inline constraint: 'regex(^\w\w(-\w\w|)$'`. Any ideas how to go on from this? – Tomas Aschan Feb 03 '15 at 08:02
  • Nvm; the posted solution was missing an ending parenthesis and curly brace, opened by `{...:regex(` - adding them, it works =) (I've edited the answer to include this change.) – Tomas Aschan Feb 03 '15 at 08:09
  • @TomasLycken oh sorry, wasn't able to reply as I was in school. Anyway, glad to see that you were able to solve the problem. – Amit Joki Feb 03 '15 at 11:25