Is it possible to call the same method in all Controller Asp.. net mvc without having to repeat the code?

Asked

Viewed 860 times

1

In my Controller Home, I have this:

   /// <summary>
        /// Aqui estou trocando o idioma da página de acordo cam a seleção do 
        /// usuário.
        /// </summary>
        /// 

        public ActionResult AlteraIdioma(string LinguagemAbreviada)
        {

            if (LinguagemAbreviada != null)
            {
                Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(LinguagemAbreviada);
                Thread.CurrentThread.CurrentUICulture = new CultureInfo(LinguagemAbreviada);

            }

            //aqui estou gravando o cookie com o idioma para que seja recuperado no Global.asax
            HttpCookie cookie = new HttpCookie("Linguagem");
            cookie.Value = LinguagemAbreviada;
            Response.Cookies.Add(cookie);

            return View("Index");
        }

It changes the language of the page and records a cookie for the navigation to follow in the chosen language, but I wonder if I can call this in all controllers without having to repeat, how would it look? Thanks

  • I don’t know what the doubt is. Power can, but it depends on what you want to do, if you really need it, if that’s how it should be. It would probably be better to do it another way, but it’s not easy to give an example without a context. The basic thing is that you should just take the cookie and do what you want without calling this method. It can, but it would not make sense to do it. I have doubts until this method is right. By the way, I noticed that you accept anything that comes on the server, right? http://answall.com/q/13298/101

3 answers

1

There is a native Framework resource for this, called ASP.NET MVC Filter Types.

Basically, you can define an Action filter to be executed at the beginning or end of each request to add your information. For example:

public class AlteraIdiomaFilterAttribute : ActionFilterAttribute 
{
    // nesse caso, adiciona ao fim da execução de uma Action
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        // pega o valor da requisição, no seu caso uma QueryString
        string linguagemAbreviada = filterContext.HttpContext.Request.Params["LinguagemAbreviada"];

        if (linguagemAbreviada != null)
        {
            // tome cuidado ao usar informações vindo do usuário!
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(linguagemAbreviada);
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(linguagemAbreviada);
        }

        HttpCookie cookie = new HttpCookie("Linguagem");
        cookie.Value = linguagemAbreviada;

        // adiciona no context, que ele controla o Response que será processado de fato
        filterContext.HttpContext.Response.Cookies.Add(cookie);
    }
}

You use Action filter global by logging into Global.asax:

protected void Application_Start()
{    
    GlobalFilters.Filters.Add(new AlteraIdiomaFilterAttribute());
}

If you are using the standard ASP.NET MVC 5 template, it creates for you the Filterconfig class and already calls the registration method in Global.asax, just add your filter:

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new AlteraIdiomaFilterAttribute());
    }
}   

In the case of ASP.NET Core, the official documentation instructs to add the global filters in Statup:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc(options =>
    {
        options.Filters.Add(new AlteraIdiomaFilterAttribute());
    });

    services.AddScoped<AddHeaderFilterWithDi>();
}

1

Basically, to get what you need, there are 3 possibilities (2 of which have already been explained very well above):

  1. using a Filter, so you get this functionality globally;
  2. using inheritance, so you will have this functionality locally, this You have to include the call code in each action;
  3. using some AOP (aspect orientation) tool to embed your code snippet before execution of each method, so you can choose to do by class, method, library;

Each of these solutions has its strengths and weaknesses. The choice is yours.

0

One of the ways to reuse code between controllers would be with inheritance

I don’t know if it would be ideal to change the language, but I will keep the answer focused on the question that is to reuse.

You create a class by inheriting Controller:

public class BaseController : Controller
    {
        public void MeuMetodo()
        {
            ...
        }
    }

From there all your controllers stop using the controller inheritance and now use Basecontroller now.

public class HomeController : BaseController 
    {
        public ActionResult Index()
        {

            MeuMetodo();

            return View("Index");
        }

This is a simple and quick way to reuse.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.