2

using the following

app.UseMvc(routes =>
{
    routes.MapRoute(
       name: "beacon",
       template: "beacon/{id?}");

    routes.MapRoute(
       name: "default",
       template: "{controller=Home}/{action=Index}/{id?}");
});

http://www.example.com/beacon does what I expect and hits BeaconController

But http://www.example.com/beacon/001 does not hit any controller and goes 404

What am I missing?

1
  • Do you have an Index action method inside BeaconController accepting an input id parameter of type integer? Commented Jun 13, 2018 at 17:53

1 Answer 1

2

You specified the route pattern URL, but did not mention what controller/action should handle these type of requests.

You may specify the defaults options when defining the route

app.UseMvc(routes =>
{
    routes.MapRoute(
      name: "beacon",
      template: "beacon/{id?}", 
      defaults: new { controller = "Beacon", action = "Index" }
    );

    routes.MapRoute(
      name: "default",
      template: "{controller=Home}/{action=Index}/{id?}");
});

Assuming your Index method has a id parameter of nullable int type

public class BeaconController : Controller
{
    public ActionResult Index(int? id)
    {
        if(id!=null)
        {
            return Content(id.Value.ToString());
        }
        return Content("Id missing");    
    }
}

Another option is to remove the specific route definition from the UseMvc method and specify it using attribute routing.

public class BeaconController : Controller
{
    [Route("Beacon/{id?}")]
    public ActionResult Index(int? id)
    {
        if(id!=null)
        {
            return Content(id.Value.ToString());
        }
        return Content("Id missing");
    }
}

The reason, http://www.example.com/beacon is working is because that request structure matches to the pattern defined for the default route.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes - specify the name of the controller in the defaults. Just naming the route does not hook it to the proper controller. I'm learning - thanks Shyju!

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.