0

I want to change the URL that will access my controller, but when I do, instead of getting controller/action/id, I get controller/action?id=(the id number) in the URL.

I am using default routing in my MVC .Net Core.

 app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });

On my controller I have [Route("DifferentName/{action=index}")] for attribute routing.

I have tried adding [Route("DifferentName/{action=index}/{id?}")]

but I get an exception "RoutePatternException: The route parameter name 'id' appears more than one time in the route template."

2 Answers 2

2

These attributes are incorrect according to the documentation:

[Route("DifferentName/{action=index}/{id?}")]

[Route("DifferentName/{action=index}")]

This is how it should look like for controller when we want to only change its part of URL:

[Route("DifferentName/[action]")] [action]

[action] will be replaced by your action name when asp .net core will be resolving URLs.

More information about routing and can be found in the documentation

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

3 Comments

I have tried [Route("DifferentName/[action]")] but still get ?id= in the URL. In addition if I try to navigate to DifferentName/Action/5 I get 404. I have to put DifferentName/Action?id=5.
I have also added [Route("")] [Route("Index")] to my Index action. The only way I can access it is by DifferentName/Index. DifferentName by its self throws 404. Which according to documentation it should work. Am I missing something??
My controller also inherits a base controller. I'm pretty sure that's effecting the routing. Going to do more research.
0

but I get an exception "RoutePatternException: The route parameter name 'id' appears more than one time in the route template."

I have reproduced your error. I need to confirm with you whether the reason for your error is to add Route attribute to both controller and action.

If so, as the exception points out, you don't need to specify route repeatedly.

Modify the following settings to implement the url like 'Differentname/action/5':

    [Route("DifferentName/{action=index}")]
    public class ShowPdfController : Controller
    {
       
        public IActionResult Index()
        {
            return View();
        }

        [Route("{id?}")]
        public IActionResult Action(int id)
        {
            return View();
        }
   }

Then, you can see the test result of this setting:

enter image description here

Comments

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.