0

i write a attribute for accesslevel in asp core .

this is my code :

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class AllowAccessAttribute : Attribute, IAuthorizationFilter
{
    private readonly IDomainUnitOfWork unitofwork;
    private readonly IHttpContextAccessor httpContext;
    private readonly string _name;

    public AllowAccessAttribute(string name)
    {
        _name = name;

    }
    public string Name => _name;

    public AllowAccessAttribute(IDomainUnitOfWork unitofwork, IHttpContextAccessor httpContext)
    {
        this.unitofwork = unitofwork;
        this.httpContext = httpContext;
    }

    public void OnAuthorization(AuthorizationFilterContext context)
    {

        var userId = httpContext.HttpContext.User.Identity.GetUserId<long>();

    }

}

and use the typefilter :

   public class AutourizeAccessAttribute : TypeFilterAttribute
{
    public AutourizeAccessAttribute(string permission) : base(typeof(AllowAccessAttribute))
    {
        Arguments = new object[] { permission };
    }
}

and use that by this way :

[AutourizeAccess("Change Use Active Status")]

but when i run the code it show me this error :

Object reference not set to an instance of an object

in this line var userId = httpContext.HttpContext.User.Identity.GetUserId<long>();

whats the problem ? how can i solve this problem ????

kianoush dortaj
  • 707
  • 1
  • 6
  • 8

0 Answers0