Pouya Moradian
Pouya Moradian

Reputation: 93

How to handle different action with same route and different authorize attribute in asp .net core

I'm developing some Web-API project with ASP.Net Core 2 using some custom middleware which is translating the authorization info that it gets from a 3rd party service into a new Claim Identity and adds it to http context user claim principal. I also have implemented some custom authorization policy provider which checks the added claim identity for required permissions and roles.

Now I wanna have two actions like below on same controller with same route:

[Route("api/[controller]")]
public class StatesController : Controller
{

[Authorize("PaiedUser")]
[HttpGet(Name = "GetStates")]
public IActionResult GetStatesPaied(StateHttpRequestParameter requestResourceParameter)
{ //some code here to handle the paied user request} 

[Authorize("FreeUser")]
[HttpGet(Name = "GetStates")]
public IActionResult GetStatesFree(StateHttpRequestParameter requestResourceParameter)
{ //some code here to handle the free user request}
}

On the runtime I got this exception,

Microsoft.AspNetCore.Mvc.Internal.AmbiguousActionException: Multiple actions matched. The following actions matched route data and had all constraints satisfied:

SaMonitoring.API.Controllers.StatesController.GetStatesFree(SaMonitoring.API) SaMonitoring.API.Controllers.StatesController.GetStatesPaied(SaMonitoring.API)

How can I achieve this behavior ?

Upvotes: 3

Views: 2024

Answers (1)

UmmmActually
UmmmActually

Reputation: 217

I think the problem here is that the roles are not mutually exclusive as far as MVC is concerned. Someone could fall into both conditions which is what makes it ambiguous. I think you'd be better off checking the user's role inside a single function and providing results appropriately.

Upvotes: 1

Related Questions