0

I am trying to route asp.net core application.

I have having this scenario:

[Route("/{user}")]
public IActionResult FirstAction(string user)
{
    // Code
}

[Route("/{user}/{project}")]
public IActionResult SecondAction(string user, string project)
{
    // Code 2
}

Problem i am having is that when user goes to link /something it fires both methods (// Code 1 and // Code 2) but i want only first one to fire.

How can i achieve this?

4
  • 3
    Umm, it shouldn't be possible for 2 actions to run? Could you look at the actual request URL within the action through e.g. HttpContext.Request? Commented Aug 25, 2020 at 11:13
  • let the first slash away Commented Aug 25, 2020 at 11:15
  • I do not want multiple actions, i just want multiple parameters to be passed without using ?user=. Same behavior as on github.com/{organization}/{project} Commented Aug 25, 2020 at 11:25
  • That's why my answer. The ?user is replaced with the rest path /users Commented Aug 25, 2020 at 15:55

2 Answers 2

1

Use a better REST API routing

[Route("/users/{user}")]

[Route("/users/{user}/projects/{project}")]
Sign up to request clarification or add additional context in comments.

4 Comments

I want same behavior as on github.com/{organization}/{project}
Is that also the API route? Or you are taking about the one in the browser? Because the one in the browser is managed in another place
It is browser route
But your question is about an API route? In that case they are different. And you can maintain a different routing convention from what the user sees and what happens with a backend server... The browser route can be manipulated in many different ways. But for the API I keep my suggestion of the answer I provided
0

Are you sure that both actions are fired? Which version of ASP NET Core are you using?

I tested the following:

    [HttpGet("/{user}")]
    public ActionResult<string> Test1(string user)
    {
        return "User " + user;
    }

    [HttpGet("/{user}/{project}")]
    public ActionResult<string> Test2(string user, string project)
    {
        return "User " + user + " Project " + project;
    }

The routes where explicit. If there was only one string Test1 was routed. If there were two strings Test2 was routed.


Furthermore, please note the following: If you put a leading / into the route any prefixes will be ignored.

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.