1

I have an MVC application and the UI team has requested that urls for a careers page follow this format: mydomain.com/careers/{jobTitle}/{JobCode}. I can do that in the careers controller like this:

    public ActionResult Detail(string jobTitle, string jobCode)
    {
        var model = getModelFromDb(JobCode);
        return View(model);
    }

The problem is that we look up the career info by job code not title so we end up with an unused parameter. I don't think this is best practice. Especially since you can enter whatever you want for the career title and still get the job details back. A url like this would still work: mydomain.com/careers/yourmom/1234.

I suppose we could always look up careers by title and code but that seems kind of pointless since the codes are unique.

Is there a better way to implement the extra parameter in the url and keep from allowing invalid job titles from being put in the url?

user449689
  • 3,142
  • 4
  • 19
  • 37
Bruno
  • 533
  • 1
  • 6
  • 27
  • 1
    One thing you could try is make jobTitle optional, but that means changing the url format to {JobCode}/{jobTitle} and i guess that's not an option? – Zippy Nov 15 '16 at 13:54
  • 1
    have a look at this question and answer http://stackoverflow.com/questions/24678045/routing-optional-parameters-in-asp-net-mvc-5 . can use optional parameter in routing – Emil Nov 15 '16 at 13:56
  • 1
    I guessing you might be wanting a 'slug' route (where including only `jobCode` will result in a url with both the `jobcode` and `jobTitle`)? If so, refer [this answer](http://stackoverflow.com/questions/30349412/how-to-implement-url-rewriting-similar-to-so/30363600#30363600) –  Nov 15 '16 at 21:17

2 Answers2

2

You can create your own custom route constraint, this will allow to match only routes that contain jobtitle that match the jobcode.

You will have to inherit from the IRouteConstraint interface and implement the Match method. One of the parameters that the method receive is a RouteValueDictionary.

It is a collection of key/value pairs containing the routing parameters. You can use them to look up the job title and make sure it is coherent with the job code.

See this example for more info.

In this way you will be able to receive only correct routes and reject incorrect routes like mydomain.com/careers/yourmom/1234

user449689
  • 3,142
  • 4
  • 19
  • 37
0

What we ended up doing is passing both parameters to the controller(jobTitle and jobCode), looking up the record by jobCode, and validating that the record's slug matches the jobTitle passed in(all case insensitive). This way we prevent bogus urls from returning job detail pages and we keep the UI team happy.

Bruno
  • 533
  • 1
  • 6
  • 27