I upgraded a web API in .NET Framework 4.6 to 8.0 web API Core and got an error message from the IsAuthorized
method:
The type or namespace name 'HttpActionContext' could not be found (are you missing a using directive or an assembly reference?)
public class CustomApiAuthorizeAttribute : AuthorizeAttribute
{
[Inject]
public IUnitOfWork UnitOfWork { private get; set; }
protected override bool IsAuthorized(HttpActionContext actionContext)
{
var principal = actionContext.RequestContext.Principal;
if (!principal.Identity.IsAuthenticated)
return false;
return UnitOfWork.IsUserAuthorized(principal.Identity.Name.Substring(5));
}
}
How can I resolve this?
You can achieve that by using filters:
public class CustomApiAuthorizeAttribute :Attribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationFilterContext context)
{
if(context.HttpContext.User.Identity != null && context.HttpContext.User.Identity.IsAuthenticated)
{
// do your work
}
}
}