简体   繁体   English

ASP.NET MVC 5 未定义参数的包罗万象的路由

[英]ASP.NET MVC 5 catch-all route for undefined parameters

I have a default route with an optional id parameter that matches a lot of controller methods, which is desired.我有一个带有可选id参数的默认路由,该参数与许多 controller 方法相匹配,这是所需的。

routes.MapRoute(
  name: "Default",
  url: "{controller}/{action}/{id}",
  defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
);

Most controllers define the id param as an int rather than a nullable int.大多数控制器将 id 参数定义为 int 而不是可为空的 int。 For example:例如:

public ActionResult Detail(int id)
{
  var model = GetModel(id);
  return View(model);
}

The problem is that, in this large web app, occasionally some errant code will direct the user to a path without the id.问题是,在这个大型 web 应用程序中,有时一些错误代码会将用户引导到没有 id 的路径。 For example, /ControllerName/Detail .例如, /ControllerName/Detail The default route is invoked, but an exception is logged because of the missing parameter:调用了默认路由,但由于缺少参数而记录了异常:

System.ArgumentException: The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Detail(Int32)'

There will be an effort to find out why such a request is happening in the first place, but I'd also like to avoid logging the exception, and show a 404 page instead of a 500 page.首先将努力找出为什么会发生这样的请求,但我也想避免记录异常,并显示 404 页面而不是 500 页面。 The questions I've seen provide solutions for an unknown controller or action, but not a param that the default route defines as optional, but the action method defines as required.我看到的问题为未知的 controller 或操作提供了解决方案,但不是默认路由定义为可选的参数,但操作方法定义为必需。

I've tried adding my "catchall" route before the default, with id given a value of 0:我尝试在默认路由之前添加我的“catchall”路由,id 的值为 0:

routes.MapRoute(
  name: "CatchAll",
  url: "{controller}/{action}",
  defaults: new { controller = "Home", action = "Index", id = 0 },
);

This prevents the exception, but I want to show a 404 error page.这可以防止异常,但我想显示 404 错误页面。 Is there any way to do this in the route config, instead of changing every action method to expect an int? id有没有办法在路由配置中执行此操作,而不是更改每个操作方法以期望一个int? id int? id and then redirecting to the 404 page if .id.HasValue ? int? id然后重定向到 404 页面如果.id.HasValue

In my last project, I had a similar issue.在我的上一个项目中,我遇到了类似的问题。 This is what worked for me.这对我有用。

Try using int?尝试使用int? while excepting parameters.参数除外。

If it doesn't work, use string and then convert it to an integer.如果不起作用,请使用字符串,然后将其转换为 integer。

[HttpGet]
public ActionResult MyFunction(string val)
{
   int n = Convert.ToInt32(val);
   ...logic
}

While implementing pagination with PagedList.MVC I used int? page在使用 PagedList.MVC 实现分页时,我使用了int? page int? page and it didn't throw an exception. int? page ,它没有抛出异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM