C# 是否可以在ASP.Net属性中设置必需的属性?

C# 是否可以在ASP.Net属性中设置必需的属性?,c#,asp.net,C#,Asp.net,我在谷歌上快速搜索了一下,没有找到任何方法,所以如果这个问题是重复的,我很抱歉 我有一门课,像: using System.Web; using System.Web.Mvc; namespace Authorization { public class AuthorizeAttribute : ActionFilterAttibute { public string Address { get; set; } public override

我在谷歌上快速搜索了一下,没有找到任何方法,所以如果这个问题是重复的,我很抱歉

我有一门课,像:

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);
        }
    }
}
问题是,每当我将此属性添加到项目中的其他类时,可以用两种方式定义它。第一种方法基本上类似于调用属性的默认构造函数;没有数据传入。第二种方式允许指定
地址


我觉得我不能删除第一个选项,因为它可能是通过我创建的父类指定的。但有可能只有第二种选择吗?这将非常理想。

我认为您希望使用构造函数来设置属性属性(或字段),因此类似以下内容:

public class AuthorizeAttribute : ActionFilterAttibute
{
    private readonly string _attribute;

    public AuthorizeAttribute(string attribute)
    {
        _attribute = attribute;
    }
}

创建一个以
地址
为参数的构造函数。看起来很有效。如果你把它写下来作为答案,我也会接受的。另外,如果您知道有关Asp.Net属性的任何相关信息源,我将非常感谢您的帮助。谢谢。这是一个复制品,但是如果能看到5.0++的实现就好了@ChaimEliyah你所说的5.0++实现是什么意思?对不起,是C#5.0还是C#6.0。我链接到的答案有一个C#2.0(?)实现。它使用自动属性和支持字段。现在看来没必要了。