you code says {id} is optional. if it is not optional for some routes, define that routes requiring the {id} using routing attributes may be a better solution for this use case.
MVC Routing force parameter
Hello Everyone,
in my asp.net MVC project, following default mapping is used.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Login", id = UrlParameter.Optional }
);
}
some urls may contain a id parameter while some pages don't
how to validate the urls, which must need a id parameter to avoid object reference not set error.
if i access "TimeSheet/Employee/10" it works . if i try to access, "TimeSheet/Employee/" it should redirect to some-other page instead of object reference not set error.
also "TimeSheet/EmpList" should work without expecting for additional parameter.
please guide. Thanks for any help.
2 answers
Sort by: Most helpful
-
-
AgaveJoe 29,786 Reputation points
2022-07-05T22:55:38.443+00:00 Declare a nullable Id parameter. Redirect if the id is null.
[HttpGet] public IActionResult Login(int? id) { if(!id.HasValue) { return RedirectToAction("MissingId"); } return View(); }