开发者

Attribute help with Routing, compiler error

I have cre开发者_如何学编程ated a custom attribute called RouteAttribute:

[AttributeUsage(AttributeTargets.Property)]
public class RouteAttribute : Attribute
{
    public string Url { get; set; }
    public bool CheckPhysicalUrlAccess { get; set; }
    public RouteValueDictionary Defaults { get; set; }
    public RouteValueDictionary Constraints { get; set; }
    public RouteValueDictionary DataTokens { get; set; }
}

It is used to add routing via attribute on my url helper class that contains a list of urls in my site, so i have a easy way to manage my site urls.

Having a problem with adding a default though, getting compiler error:

[Route("~/MyPage/Home.aspx", new RouteValueDictionary { { "query", "value" } })]
public string HomePage
{
  get { return "Home" }
}

To avoid confusion, the value is set to the routeurl, physical url is from attribute, reason for this is, I am converting an existing site, and rather than changing links everywhere, once I'm done with page, I go to my class and change the physical url to new page

Giving an error:

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type


The argument values for an attribute constructor are stored in metadata. That puts severe restrictions on what you can specify. Just simple value types, a Type from typeof and a simple one dimensional array of these values. No code is allowed, which is what the compiler complains about, the new operator requires code.

There are no constrictions on what you can do in the body of the attribute constructor, that code runs later when reflection code inspects the attribute. Suggesting something similar to this:

public class RouteAttribute : Attribute
{
    public RouteAttribute(string url, string query, string value) {
       this.url = url;
       this.dunno = new RouteValueDictionary(query, value);
    }
    // etc..
}
...
[Route("~/MyPage/Home.aspx", "query", "value")]
public string HomePage
{
  get { return "Home" }
}

This obviously needs work, I have no idea what the dictionary means. Be careful about it having side-effects or requiring resources, you don't know the runtime state when the attribute gets constructed.


An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

The error tells you exactly what the problem is.

As

new RouteValueDictionary { { "query", "value" } }

is not a constant expression, not a typeof expression and not an array creation expression, this is not legal.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜