Last active
February 16, 2023 21:04
-
-
Save NamelessG0d/1a9f3bbb8adf6d53eab84a767613ec82 to your computer and use it in GitHub Desktop.
Custom Controller Attribute to execute code before execution (C# Asp.Net Mvc)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.AspNetCore.Mvc; | |
using Microsoft.AspNetCore.Mvc.Filters; | |
using System.Security.Claims; | |
namespace ASP.Attributes | |
{ | |
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] | |
public class AccessLevelAttribute : ActionFilterAttribute | |
{ | |
private readonly int _role_level; | |
public AccessLevelAttribute() { _role_level = 0; } | |
public AccessLevelAttribute(int role) | |
{ | |
_role_level = role; | |
} | |
public override void OnActionExecuting(ActionExecutingContext context) | |
{ | |
var org_Result = context.Result; //should be null but just in case | |
context.Result = new UnauthorizedResult(); | |
//Example using Identity to store userId (JWT) | |
var identity = context.HttpContext.User.Identity as ClaimsIdentity; | |
if (identity == null) | |
return; | |
var user_id = identity.FindFirst("UserId"); | |
if (user_id == null) | |
return; | |
var userRole = User.GetUser(user_id.Value).Role; | |
if (userRole >= RoleLevel) | |
{ | |
context.Result = org_Result; | |
base.OnActionExecuting(context); | |
} | |
} | |
public int RoleLevel => _role_level; | |
} | |
} | |
//Don't forget to add the attr to the scope | |
services.AddScoped<AccessLevelAttribute>(); | |
//Example in a controller | |
namespace ASP.Controller | |
{ | |
[ApiController] | |
public class UserController | |
{ | |
[HttpGet] | |
[AccessLevel(7)] //check Role >= 7 | |
public IActionResult GetUserList() | |
{ | |
return new JsonResult(UserManager.UserList); | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment