How to get the current execution area?

I have a class used by controllers in [Project]. Controllers and controllers in different areas. How can I determine where the controller is located? (I think I could look at the properties of HttpContext.Current.Request, but I'm looking for the β€œcorrect” MVC method). Thanks.

I.e:

[Project].Helpers // called by: [Project].Controllers [Project].Areas.[Area].Controllers // how could I determine the caller from [Project].Helpers? 
+6
source share
2 answers

We deliberately did not find a way to get the current area name from the MVC request, since "area" is just a route attribute. This is unreliable for other purposes. In particular, if you want your controllers to have some attribute (think of an abstract term, not the System.Attribute class) that the helper can use, then these attributes should be found by the controllers themselves, and not in this area.

As a practical example, if you want some logic (for example, an action filter) to run in front of any controllers in a certain area, you must associate the action filter with these controllers directly. The easiest way to do this is to associate some MyAreaBaseController with this filter, and then each controller that you logically want to associate with this scope to subclass this type. Any other use, such as a global filter, that looks at RouteData.DataTokens ["area"] for a decision, is unsupported and potentially dangerous.

If you really need to get the current area name, you can use RouteData.DataTokens["area"] to find it.

+16
source

You can get the region string from RouteData :

 // action inside a controller in an area public ActionResult Index() { var area = RouteData.DataTokens["area"]; .... return View(); } 

.. so that you can make an extension method for such helpers:

 public static class SomeHelper // in [Project].Helpers { public static string Area(this HtmlHelper helper) { return (string)helper.ViewContext.RouteData.DataTokens["area"]; } } 
+4
source

All Articles