StructureMap Error When Invalid Controller

I use a Structural map similar to Rob Conery’s MVC showcase, and I have an AdminController, and therefore, to get to it, I simply type:

website/Admin/action 

however, if I skip the controller name spell, I get the following error:

Exception Details: System.ArgumentNullException: The value cannot be null. Parameter Name: Key

An error occurs on this line:

 Controller controller = ObjectFactory.GetInstance(controllerType) as Controller; 

Does anyone have any ideas on how I can handle this error or not allow it to happen at all and maybe just go to page 404?

Greetings in advance

+4
source share
2 answers

The problem is that if there is no controller with the expected type name (i.e. if the user types β€œ Amdin ”, the ControllerFactory base class will look for the β€œ Amdin controller ” and will not find it, but it will still call your overriden method). In this case, the variable controllerType will be zero. That way, you can just check it for null before the line you specified, and then (if it is zero):

A) Make a spelling correction, for example cfeduke suggests

or B) just throw an HttpException with a status code of 404 (this should result in the 404 error you're looking for).

NOTE. If you're doing spelling corrections, you should probably do Response.Redirect to the new URL, and not just silently load the correct controller, so the address bar will change to reflect spelling

+6
source

You have a couple of different options (or, if you want, two things that you can combine to solve). To remove some of the potential problems between the chair and the address bar, you can implement the SoundEx solution in C # using the new routing structure to potentially capture some spelling errors and redirect them to the expected URL (and / or add routes for what you think common misspellings or queries). However, this is not a solution that will completely solve the problem, so you need to look at creating custom error pages for your application.

+1
source

All Articles