How can I handle a null parameter dictionary error for MVC3 routes?

Most of the routes used are based on the default route defined in the standard MVC3 application:

routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional }); 

However, if I have the route "/ Book / Update / 1" and "1" is disabled, because the user entered the address manually without 1, an error with zero parameters is generated. Obviously, my route requires this 1 and is not optional, but I will not define my own route for each of my actions. If I turn on custom errors, I'm not sure what type of error it will redirect to the correct html error page.

Question: How do I handle this error, like 404? I do not see any problems with this approach, because the reality is that the rejection of the identification number in the route is the same as that found in 404.

Or am I missing something while developing my routes? Seems pretty straightforward to me.

Thanks.

Update: I appreciate the answers below. They are both reasonable approaches. For clarity in my question, let me clarify a little more. The route "/ Book / Update / 1" should, in my opinion, have only one goal. Refresh the book 1. Any other deviation from this should fail and redirect to 404. I see nothing in this except a static html page that does not exist. I can argue about a function that is simply not included in .net, I just thought it might be easier.

Update2: Should have dug a little deeper. There is a great example here . I found the second answer most helpful.

+4
source share
2 answers
 public ActionResult Update(int? id) { if (!id.HasValue) return HttpNotFound(); //Debug.Assert(id.Value != null); ... } 
+2
source

I had and this problem, what I did was create a reusable action filter where I set the required parameters.

Action Filter:

  public class RequiredActionParameters : ActionFilterAttribute { private readonly IEnumerable<string> _parameters; public RequiredActionParameters(params string[] parameters) { _parameters = parameters; } public override void OnActionExecuting(ActionExecutingContext filterContext) { if (!filterContext.IsChildAction && !filterContext.RequestContext.HttpContext.Request.IsAjaxRequest()) { foreach (var parameter in _parameters) { if (filterContext.ActionParameters[parameter] == null) { filterContext.Result = new RedirectResult("/Error/NotFound"); break; } } } } } 

About the action in the controller:

  [RequiredActionParameters("restaurantId", "testId")] public ActionResult Details(long restaurantId, long testId) { View(); } 

I tested it with the elmah error log tool and did not report any errors.

0
source

Source: https://habr.com/ru/post/1401480/


All Articles