[英]How to retrieve controller and action names from Html.Action that is rendered from different controller and action in ASP.NET MVC
[英]How to get the MethodInfo of action by controller and action names in asp.net core mvc?
我需要在我的Taghelper(asp.net core2.0)中获取操作的MethodInfo。 控制器名称,动作名称(或区域名称)是我唯一拥有的东西。 而不是在启动时执行所有操作。 有什么方法可以在运行时动态获取操作的MethodInfo(例如使用反射)吗?
您可以通过以下方式构建属性集合:
publicstring GetHyperlinkAttributes<TEntity>(string name)
{
PropertyInfo property = typeof(TEntity).GetProperty(name);
object[] attributes = property.GetCustomAttributes(false);
var collection = new List<string>();
foreach(Attribute attribute in attributes)
{
var hyperlink = attribute as HyperlinkAttribute;
if(!string.IsNullOrEmpty(hyperlink?.Target)
return hyperlink.Target;
}
return String.Empty;
}
因此,对于上述内容,如果您创建了一个属性,则它将通过name参数在给定属性的传递给该方法的对象上寻找Target
属性。 如果需要扩展,可以通过typeof(TEntity).GetProperties()
遍历整个对象。
我添加了一些逻辑,以使您知道, GetCustomAttributes
将返回属性上的所有属性。 因此,如果开发人员向该字段添加了非HyperLinkAttribute
属性,则使用HyperLinkAttribute
转换。 这可以清理,但想通了,我会提醒您注意的陷阱。
因此,如果存在以下情况:
[Target("https://microsoft.com")]
public string Example { get; set; }
上面的方法将返回https://microsoft.com
。
现在,棘手的部分-您的标记助手。
public class TargetTagHelper : TagHelper
{
public string DestinationName { get; set; }
public override Process(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "a";
var url = GetHyperLinkAttributes<Navigation>(DestinationName);
output.Attributes.SetAttribute("href", url);
output.Content.SetContent(url);
}
}
因此,以上内容可以实现您的目标,但有一些缺点:
但是,如果这些限制很好,则应允许:
<target destination-name="Microsoft">Microsoft</target>
可能存在一些错误,我很快就写了。 但这应该是一个坚实的起点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.