MVC Routing force parameter

Jayannet-2659 21 Reputation points
2022-07-05T06:23:17.917+00:00

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.

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,254 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 56,026 Reputation points
    2022-07-05T16:12:44.197+00:00

    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.


  2. AgaveJoe 26,201 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();  
      
    }