0

I have an MVC app that has 2 controllers.

Home and Details.

Details Controller:

public ActionResult Index(long startTime, long endTime, string kpiName)
{
   // create my viewmodel.
   return View(detailsViewModel);
}

This page should only be called if the user clicks a details button on another page. The problem is the user can directly navigate to http://localhost:54816/Details and a YSOD is shown with the error

The parameters dictionary contains a null entry for parameter 'startTime' of non-nullable type 'System.Int64' for method 'System.Web.Mvc.ActionResult Index(Int64, Int64, System.String)' in 'SentlianKPI.Controllers.DetailsController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters

I tried adding a route as shown below:

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

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

With the idea being that the id is not optional so it will fail through to the Home controller.

It's not working though, how do I setup a route to catch this and redirect the user?

1
  • You can't stop a user entering a url in the address bar. Commented Apr 12, 2017 at 10:39

2 Answers 2

1

You could make the paramaters optional and then redirect them if they are null? The below code isn't tested.

  public ActionResult Index(long? startTime = null, long? endTime = null, string? kpiName = null)
    {
      if(startTime == null || endTime == null || kpiName == null){
        return RedirectToAction("ActionName", "ControllerName");
       }
       // create my viewmodel.
       return View(detailsViewModel);
    }
Sign up to request clarification or add additional context in comments.

Comments

0

Why not make the parameter to your controller method take a nullable int and then redirect from the controller method when the value is null? You could create a ReRouteIfNull filter attribute to decorate controller methods (and have it take a route parameter name and a redirect action) so that you don't have to add check and redirect logic to each controller method where you want this behavior (assuming you need it more than once).

2 Comments

Sounds nice. Could you provide a code snippet for it?
No, but here is an example of how to access route parameters from within a filter which you could use for your redirect logic starting point: stackoverflow.com/questions/8622482/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.