MVC Web API 2 - Using custom attribute on action

6.9k views Asked by At

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

1

There are 1 answers

0
Eric On BEST ANSWER

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