Mike Hofer
Mike Hofer

Reputation: 17002

Why is my ASP.NET MVC route configuration causing an HTTP 404 error?

The issue arises with a map route I have added to my RouteConfig.cs file, which maps routes to my Topic controller.

Here's my RegisterRoutes method, from global.asax:

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
    name: "ArticleByTitle",
    url: "{controller}/{action}/{title}/{category}",
    defaults: new { controller = "Topic", action = "Get", category = UrlParameter.Optional }
);

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

The Topic controller contains the specified action method:

namespace Wiki.Controllers
{
    public class TopicController : Controller
    {
        public ActionResult Get(string title, string category)
        {
            var topics = this.GetTopicsList();
            var count = topics.Count(t => t.Category.Equals(category, StringComparison.CurrentCultureIgnoreCase)
                                          && t.Title.Equals(title, StringComparison.CurrentCultureIgnoreCase));
            if (count > 1)
            {
                return RedirectToAction("Resolve", new { title = title });
            }

            if (count == 0)
            {
                return new HttpNotFoundResult();
            }

            var selectedTopic = this.GetTopicsList().FirstOrDefault(t => t.Title.Equals(title, StringComparison.CurrentCultureIgnoreCase));
            return RedirectToAction("Display", new { topic = selectedTopic });
        }

    }
}

However, this method is never invoked. Instead, I am receiving an HTTP 404 error when I attempt to reach it through a link in the application that looks like this:

<a href="/topic/display/MyTopic">MyTopic</a>

I am assuming that there is something wrong with my routing configuration, but for the life of me, I can't see what it is. Could someone kindly point me in the right direction?

Upvotes: 1

Views: 255

Answers (3)

Tony
Tony

Reputation: 96

For the Get action to be invoked your URL would need to look like this:

<a href="/topic/get/mytitle/mycategory"></a>

You should also generate the link by using the Html ActionLink helper like this:

@Html.ActionLink("MyTopic", "Get", "Topic", new { title = "sometitle"}, null)

Upvotes: 1

Dimitar Dimitrov
Dimitar Dimitrov

Reputation: 15138

It seems that in your href you're missing your action (which in your case is Get)

Upvotes: 1

Sparky
Sparky

Reputation: 15085

Try using the following syntax

action="@Url.Action("Go", "Home")" 

for your HREF link.

Upvotes: 0

Related Questions