How can I return something in the constructor to use it in my class?

0

I have an action filter to make a log in a class called LogActionFilter which has its respective methods to perform each specific task, and from my control I call this filter as follows [LogActionFilter] up there all right .

The problem is that I need to pass a custom message to the class of the action filter style: [LogActionFilter("Mi mensaje de log")] for my class to receive it and be able to use it in the other methods of it.

I know I must use a constructor for it, but I do not know how to retrieve the data to use in my other methods that are outside the constructor.

My Class or Action Filter:

public class LogActionFilter : ActionFilterAttribute{
    public LogActionFilter(string msg){

    }

    public override void OnActionExecuting(ActionExecutingContext filterContext){
        Log("OnActionExecuting Firxt", filterContext.RouteData);
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext){
        Log("OnActionExecuted", filterContext.RouteData);
    }

    public override void OnResultExecuting(ResultExecutingContext filterContext){
        Log("OnResultExecuting", filterContext.RouteData);
    }

    public override void OnResultExecuted(ResultExecutedContext filterContext){
        Log("OnResultExecuted", filterContext.RouteData);
    }

    private void Log(string v, RouteData routeData){
        var controllerName = routeData.Values["controller"];
        var actionName = routeData.Values["action"];
        var message = String.Format("{0} controller:{1} action:{2}", v, controllerName, actionName);
        Debug.WriteLine(message, "Action Filter Log");
    }
}

My Controller:

[LogActionFilter("SUCCES")]
public class HomeController : Controller{
    public ActionResult Index(){
        return View();
    }

    public ActionResult About(){
        ViewBag.Message = "Your application description page.";
        return View();
    }

    public ActionResult Contact(){
        ViewBag.Message = "Your contact page.";
        return View();
    }
}
    
asked by vcasas 03.07.2018 в 18:15
source

1 answer

0

I solved it in the following way, I do not know if it will be "correct".

My constructor:

private string message;

public LogActionFilter()
{
}

public LogActionFilter(string msg)
{
    this.message = msg;
}

public string Message
{
    get => message;
    set => message = value;
}

But when I inspect what the parameter msg contains, it tells me ERROR, I do not know why it happens ... but it works fine.

    
answered by 03.07.2018 / 18:30
source