开发者

How to get currently executing area?

开发者 https://www.devze.com 2023-01-30 06:46 出处:网络
I have a class used by controllers at [Project].Controllers and by controllers at different areas. How could I determine where the controller is at? (I guess I could look at the HttpContext.Current.Re

I have a class used by controllers at [Project].Controllers and by controllers at different areas. How could I determine where the controller is at? (I guess I could look at the HttpContext.Current.Request's properties -but I am looking for a "proper" MVC way). Thank you.

That is:

[Project].Helpers // called by:
[Project].Controllers
[Projec开发者_JAVA百科t].Areas.[Area].Controllers
// how could I determine the caller from [Project].Helpers?


We purposefully did not expose a way to get the current area name from an MVC request since "area" is simply an attribute of a route. It's unreliable for other uses. In particular, if you want your controllers to have some attribute (think of the abstract term, not the System.Attribute class) which can be used by the helper, then those attributes must be found on the controllers themselves, not on the area.

As a practical example, if you want some logic (like an action filter) to run before any controllers in a particular area, you must associate the action filter with those controllers directly. The easiest way to do this is to attribute some MyAreaBaseController with that filter, then to have each controller that you logically want to associate with that area to subclass that type. Any other usage, such as a global filter which looks at RouteData.DataTokens["area"] to make a decision, is unsupported and potentially dangerous.

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


You should be able to get the area string from RouteData:

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

.. so you can make an extension method for helpers like this:

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

精彩评论

暂无评论...
验证码 换一张
取 消