简体   繁体   中英

How to get the MethodInfo of action by controller and action names in asp.net core mvc?

I need to get the MethodInfo of action in my Taghelper(asp.net core2.0). The controller, action,(or maybe area) names are the only things that I have. Instead of getting all actions at startup. Is there any way to dynamically get the MethodInfo of action(like using reflection) at runtime?

You could build a collection of attributes, in the following manner:

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;
}

So for the above, if you created an attribute, it would look for the property Target on the object you've passed to the method, for a given property via the name parameter. You could loop through an entire object via typeof(TEntity).GetProperties() should you desire to expand.

I added some logic, to make you aware, GetCustomAttributes will return all attributes on your property. So the line with the cast, would be for if a developer adds a non HyperLinkAttribute attribute to the field. This could be cleaned up, but figured I'd alert you to the pitfall.

So if the following exist:

[Target("https://microsoft.com")]
public string Example { get; set; }

The above method would return https://microsoft.com .

Now, the tricky part- Your tag helper.

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);
     }
}

So the above accomplishes your goal, but has some drawbacks:

  • In this example, I create an object called navigation.
  • Looking for a property, the right value would need to be in markup.
  • Difficult troubleshooting and easily broken, if attribute or object aren't mapped correctly.

But if those limitations are fine, it should allow:

<target destination-name="Microsoft">Microsoft</target>

Some errors may exists, I wrote this quickly. But this should be a solid starting point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM