2

I did some quick Googling and didn't come up with any way to do this, so I apologize if this question is a duplicate.

I have a class like:

using System.Web;
using System.Web.Mvc;

namespace Authorization
{
    public class AuthorizeAttribute : ActionFilterAttibute
    {
        public string Address { get; set; }

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (HttpContext.Current.Request.UserHostAddress != Address)
                context.Result = new HttpStatusCodeResult(403);

            base.OnActionExecuting(context);
        }
    }
}

The problem is that whenever I add this attribute to other classes in my project, it can be defined two ways. The first way is basically like calling the default constructor for the attribute; no data is passed in. The second way allows Address to be specified.

I have a feeling that I can't remove the first option, because it's probably specified somehow through the parent class of the one I created. But is it possible to only have the second option? This would be ideal.

Brian Gradin
  • 2,165
  • 1
  • 21
  • 42
  • 3
    Create a constructor which takes the `address` as argument. – a-ctor Jun 14 '16 at 20:33
  • Looks like that works. If you write that up as an answer I'll accept it as such. Also, if you know of any relevant sources of information about Asp.Net attributes, I'd appreciate hearing of them. Thanks. – Brian Gradin Jun 14 '16 at 20:36
  • It is a duplicate, but it would be nice to see a 5.0++ implementation... http://stackoverflow.com/a/10794405/2496266 – Chaim Eliyah Jun 14 '16 at 20:42
  • @ChaimEliyah what do you mean by 5.0++ implementation? – a-ctor Jun 14 '16 at 20:46
  • Sorry, C# 5.0 or C# 6.0. The answer I linked to has a C# 2.0(?) implementation. It uses auto-properties with backing fields. Seems unnecessary, now. – Chaim Eliyah Jun 14 '16 at 20:49
  • To disable the default constructor, you can declare it as private (http://stackoverflow.com/questions/2875581/prevent-usage-of-default-constructor). – ConnorsFan Jun 14 '16 at 21:06

1 Answers1

3

I think you want to use a constructor to set the Attribute property (or field), so something like this:

public class AuthorizeAttribute : ActionFilterAttibute
{
    private readonly string _attribute;

    public AuthorizeAttribute(string attribute)
    {
        _attribute = attribute;
    }
}
chandler
  • 1,134
  • 1
  • 17
  • 33