如何获得当前执行区? [英] How to get currently executing area?

查看:79
本文介绍了如何获得当前执行区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由[Project] .Controllers和不同区域的控制器使用的类.我如何确定控制器在哪里? (我想我可以看看HttpContext.Current.Request的属性-但我正在寻找一种适当的" MVC方式).谢谢.

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.

也就是说:

[Project].Helpers // called by:
[Project].Controllers
[Project].Areas.[Area].Controllers
// how could I determine the caller from [Project].Helpers?

推荐答案

我们故意不公开从MVC请求中获取当前区域名称的方法,因为区域"只是路由的属性.它对其他用途不可靠.特别是,如果您希望控制器具有一些可以由助手使用的属性(请考虑抽象术语,而不是System.Attribute类),则必须在控制器本身上找到这些属性,而不是在上找到这些属性.该区域.

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.

作为一个实际示例,如果您希望某个逻辑(例如动作过滤器)在特定区域中的任何控制器之前运行,则必须直接将动作过滤器与那些控制器相关联.最简单的方法是使用该过滤器为MyAreaBaseController分配属性,然后使每个您要逻辑上与该区域相关联的控制器成为该类型的子类.不支持任何其他用法,例如查看RouteData.DataTokens ["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.

如果确实需要获取当前区域名称,则可以使用RouteData.DataTokens["area"]来找到它.

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

这篇关于如何获得当前执行区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆