3

I am attempting to create a custom ActionFilterAttribute as shown. The attribute will only contain a property of Path.

public class TestLinkAttribute : ActionFilterAttribute
{
    public string Path { get; set; }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {

    }
}

I would like to be able to access this attribute on the help pages area that web api integrates similar to this.

<td class="api-testLink">
@{ 
var attrColl = api.ActionDescriptor.GetCustomAttributes<TestLinkAttribute>();
      if(attrColl.Count > 0)
      {
          <p>@attrColl[0].Path</p>
      }
}
</td>

I decorated the action like this.

 [TestLink(Path = "api/surveys/72469282/responses")]
 public string GetQuestions(int id)
 {
 }

This is completely new territory to me and i have done a bit of research but can't / don't know if there is a quick way to accomplish this. Currently the output is empty as the attribute collection is never > 0

4
  • I've built a simple version of this, creating a custom attribute, assigning it to an Action and then pulling the attribute out to display a Path property like you've shown. It all works in my sample solution. Are you able to provide an example that does not work and host it on e.g. Github? Commented Sep 1, 2017 at 12:42
  • Unfortunately I can't at the moment. It's an internal app and the company is very strict about hosting this type of thing externally. Commented Sep 1, 2017 at 16:24
  • Is there any chance something else is necessary because I am trying to access the attribute within the help area of this application and something with reflection? I can do this no problem outside of that area. Commented Sep 1, 2017 at 16:27
  • I can't think of anything else. Chances are the problem is in something that's not detailed in your question. Commented Sep 1, 2017 at 18:05

1 Answer 1

6

After further research, you must inherit from System.Web.Http.Filters when you create the custom attribute with a controller inheriting from ApiController. I was inheriting from the standard mvc ActionFilterAttribute from MVC namespace (System.Web.MVC).

using System.Web.Http.Filters;

namespace App.Extensions
{
    public class TestLinkAttribute : ActionFilterAttribute
    {
        public string Path { get; set; }

    }
}

Now when i access the attribute from the ApiGroup.cshtml in the HelpPage area, i can use the following it it will properly obtain the value.

var attrColl = api.ActionDescriptor.GetCustomAttributes<TestLinkAttribute>();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.