leo
leo

Reputation: 591

Asp.net core attribute route issue

I have this code:

[Route("Users")]
public class UserRegistrationController : Controller 
{
    [HttpGet("details/{userId}")]
    public async Task<IActionResult> UserDetails(Guid userId)
    {
        // .....
    }

    [HttpPost("Save")]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> SaveUser(UserVM userVM)
    {
        // ......
        return RedirectToAction("details", "Users", new { userId = userVM.UserId });
    }
}     

If I save the user redirectToAction generate userId as query string, this create an issue.

I mean instead of

https://localhost:5001/Users/Details/5de304c7-4c69-4819-c879-08d90306b555 

redirect to action creates the URL as

https://localhost:5001/Users/Details?userId=5de304c7-4c69-4819-c879-08d90306b555 

which causes a 404 error.

How do I solve this issue? I want to pass userId in route as below

https://localhost:5001/Users/Details/5de304c7-4c69-4819-c879-08d90306b555

Thanks in advance.

Upvotes: 0

Views: 44

Answers (1)

leo
leo

Reputation: 591

The issue was, the action method UserDetails need to add route [Route("details")] This will solve the issue.

[Route("Users")]
public class UserRegistrationController : Controller 
{
    [HttpGet("details/{userId}")]
    [Route("details")]
    public async Task<IActionResult> UserDetails(Guid userId)
    {
        // .....
    }

    [HttpPost("Save")]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> SaveUser(UserVM userVM)
    {
        // ......
        return RedirectToAction("details", "Users", new { userId = userVM.UserId });
    }
}     

Upvotes: 0

Related Questions