developer82
developer82

Reputation: 13713

ASP.NET MVC - create custom route without a fallback

I'm creating an MVC project and I have the following link that leads to a list of websites for the logged in user:

http://[server]/Members/Websites

now I would like to add a new custom route under the websites part of the user that will lead to a service connection page:

http://[server]/Members/Websites/Connect-to-service/999

where "999" is the id of the website that is being connected.

I've defined the following route for that manned (placing it above the default route):

routes.MapRoute(
    name: "myRoute",
    url: "Members/Websites/Connect-to-service/{id}",
    defaults: new { controller = "Members", action = "Connect_To_Service" }
);

now, if I enter the url "http://[server]/Members/Websites/Connect-to-service/999" it loads my page fine.

if I enter the url "http://[server]/Members/Websites/Connect-to-service/" it loads the websites page.

what I would like to have is when loading "http://[server]/Members/Websites/Connect-to-service/" it will either redirect to "http://[server]/Members/Websites/" (in the browser url), or throw a page not found error.

can this be done?

thanks

Upvotes: 2

Views: 422

Answers (1)

Henk Mollema
Henk Mollema

Reputation: 46551

You could configure this in the Connect_To_Service action:

public ActionResult Connect_To_Service(int? id = null)
{
    if (!id.HasValue)
    {
        // Either:
        return RedirectToAction("Websites", "Members");

        // Or:
        return HttpNotFound();
    }

    // An id is provided. Process..
}

You might need to change your route by adding a default value for id:

defaults: new { controller = "Members", action = "Connect_To_Service", id = UrlParameter.Optional }

Upvotes: 3

Related Questions