Unknown model· unknown
from NVIDIA HelpSteer3 Preference
Show me how to create a custom Attribute based on Microsoft.AspNetCore.Authorization.
- User
Show me how to create a custom Attribute based on Microsoft.AspNetCore.Authorization.
- Assistant
public class CustomRoleAttribute : Attribute, IAuthorizationFilter { public string Role { get; }
codepublic CustomRoleAttribute(string role) { Role = role; } public void OnAuthorization(AuthorizationFilterContext context) { var authorization = context.ActionDescriptor.GetAuthorizationFilters() .FirstOrDefault(filter => filter is CustomRoleAttribute); if (authorization != null && authorization.Role == Role) { context.Result = new AuthorizationResult(); } else { context.Result = new ForbidResult(); } }}
// Usage example: [CustomRole("Admin")] public IActionResult AdminAction() { return View(); }
codeThis code snippet defines a custom authorization attribute `CustomRoleAttribute` that inherits from `Attribute` and implements the `IAuthorizationFilter` interface. The attribute takes a role as a parameter and checks if the authenticated user has the specified role. If the user has the required role, the action is allowed to execute; otherwise, access is denied. To use this custom attribute, simply decorate the desired action or controller with `[CustomRole("Admin")]`.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.