StructureMap error when invalid controller

非 Y 不嫁゛ 提交于 2019-12-30 23:14:52

问题


I am using Structure map like the MVC storefront by Rob Conery does and I have an AdminController and so to get to it I just type:

website/Admin/action

however if I miss spell the controller name I get the error below:

Exception Details: System.ArgumentNullException: Value cannot be null. Parameter name: key

There 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 goto a 404 page??

Cheers in advance


回答1:


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 "AmdinController" and won't find it, but will still call your overriden method). In that case, the controllerType variable will be null. So you can just check it for null before the line you quoted and then (if it is null) either:

A) Implement a spelling correction such as the one cfeduke suggests

or B) simply throw an HttpException with the status code 404 (that should cause the 404 error you are looking for).

NOTE: If you do a spelling correction, you should probably do a Response.Redirect to the new URL, rather than just silently loading the right controller, that way the address bar changes to reflect the spelling correction




回答2:


You have a couple different options (or if you want, two things you can combine for a solution). To remove some of the potential problems between the chair and address bar you can implement a SoundEx solution in C# using the new routing framework to potentially capture some misspellings and re-route them to the expected URL (and/or add routes for what you believe common misspellings or requests will be). This, however, isn't a solution that will fully solve the problem so you'll need to look in to implementing custom error pages for your application.



来源:https://stackoverflow.com/questions/257772/structuremap-error-when-invalid-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!