tags:

views:

36

answers:

2

Is it possible to determine if a controller exists before attempting to return the View? In my scenerio, my action value in my URL represents a user created value, and the id represents the controller. i.e.

http://mysite.com/systems/WIN1234/Configure 

...where WIN1234 is dynamically routed to the Configure action. Because I would like to keep my URLs completely hackable, I would like to determine if Configure exists before...

return View(action)

...where action is my passed in string containing Configure.

The first thing that pops into my head is looking at the assembly using reflection, but before I go that far, and because of my wet ears in MVC, I would like to know if there is a more elegant way to make this determination. i.e. ...something like:

if(DoesControllerExist(action)) return View(action)

...where DoesControllerExist is a built in MVC function.

Any of you experts have any ideas?

Thanks, George

+2  A: 

I'm not sure I get you completely correct, but is this your situation:

http://mysite.com/systems/WIN1234/Configure 

Should go to

public class SystemsController : Controller
{
    public ActionResult Configure(string theValue)  //<== This would be "WIN123" in your example
    {
        return View(theValue);
    }
}

Where you want to make sure that the following view exists:

YourMVCProject
  |
  +- Views
      |
      +- Systems
           |
           +- theValue.aspx

In that case you can use:

private bool ViewExists(string name)
{
    return ViewEngines.Engines.FindView(ControllerContext, name, null).View != null;
}

and alter your action to:

public ActionResult Configure(string theValue)  //<== This would be "WIN123" in your example
{
    if(ViewExists(theValue))
    {
        return View(theValue);
    }
    return View(fallBackView);
}

Disclaimer: all freehand code

borisCallens
A: 

I think you may be confused as to how the routing system works.

A URL is mapped to a controller and action. If there's no matching controller and action, you'll get an HTTP 404.

Thankfully, URL routes (and of course controllers) are testable so you may want to simply write unit tests for your routing configuration.

On another note, you probably do not want multiple URLs mapping to the same content without issuing an HTTP 301 (permanently moved) since it works against your PageRank.

Josh Kodroff
The routing portion isn't the issue, my custom routes are set up correctly to look at my new URL structure. I simply do not want the 404 to exist when I can intercept the bad request and direct it to the appropriate View. :)
George