Search code examples
c#asp.net-coreasp.net-core-mvccontrollercontext

Get Controller instance in AuthorizeAttribute Mvc Core Web Api


I had used below class to to control my api method request and setup some properties of BaseController class to use in methods commonly. this one is from Asp.Net Mvc Web Api

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;

[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class AuthUserAttribute : AuthorizeAttribute
{

    private string Action { get; set; }

    public AuthUserAttribute(string action)
    {
        this.Action = action;
    }

    public override void OnAuthorization(HttpActionContext actionContext)
    {
        BaseController baseController = httpContext.ControllerContext.Controller as BaseController;
        baseController.someCommenProperty = someValue;
    }
}

But when i am trying to implement same struct in Asp.Net Mvc Core Api I could not reached instance of controller that initialized. Is there any way i can get that instance.

using Microsoft.AspNetCore.Authorization;

using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Primitives;
using System;
using System.Linq;

[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class AuthUserAttribute : AuthorizeAttribute, IAuthorizationFilter
{


    private string Action { get; set; }
    public AuthUserAttribute(string action)
    {
        this.Action = action;
    }



    public void OnAuthorization(AuthorizationFilterContext context)
    {
        // how to get controller instance from context
    }
}

Solution

  • You may use context.ActionDescriptor to get the Type information on the controller.
    The controller object might be not instantiated at all at the moment of authorization check.
    You may additionally implement IActionFilter and use the controller instance in it's

    public void OnActionExecuting(ActionExecutingContext context)
    

    and

    public void OnActionExecuted(ActionExecutingContext context)