1

I know you can add an attribute to methods in C# like this,

ex1.

[HttpPost]
public void Method()
{
//code
}

Which means the attribute must be satisfied to run Method().

And I know you can stack attributes like this,

ex2.

[HttpPost]
[RequireHttps]
public void Method2()
{
 //More code
}

Which checks that both attribute1 'AND' attribute2 are satisfied before you can use Method2().

But can you 'OR' Attributes? Something like this maybe?

ex3.

[HttpPost || RequireHttps]
public void Method3()
{
  //Even more code
}

So if either attribute is satisfied you can use Method3().

Edit: Sorry was under the impression Attributes where called Annotations. Fixed that.

4
  • No, you can't. Out of curiosity, is your example academic, or is that what you're trying to accomplish? Commented Apr 18, 2012 at 14:47
  • 4
    Those are not annotations. They're attributes. Commented Apr 18, 2012 at 14:47
  • 2
    Attributes (which is what you posted as annotations) are just extra meta-data. They don't enforce anything. Commented Apr 18, 2012 at 14:48
  • @mccow002 I was trying to accomplish something like this. I'm not savvy enough to ask this question on purpose. :p Commented Apr 18, 2012 at 15:04

2 Answers 2

6

Which means the annotation must be satisfied to run Method()

That is a misunderstanding.

The [HttpPost] attribute is a directive, this method will only match a Post request. It is not a 'demand' like a security check. Only some attributes work that way.

But when considering them as 'requirements' : they work independently so that will always result in AND behaviour.

Sign up to request clarification or add additional context in comments.

3 Comments

Funny enough my group is using custom attributes for security. And I need to either annotate the method with a check for 1 of 2 scenarios or find a different way to restrict access to the method. Ideas?
Custom attribute, like you said.. and maybe a PostSharp to make it easier.. Of course, you can always do it in method - if (!Permission.Validate(user, Permisisons.DoSomething)) throw new MyException(); - kind of thing
When you write your own Attributes and use for example strings for the Privileges you can make [AuthorizeRequireOr("Admin", "Debugger")]
1

In C# they are not called annotations, but attributes.
By default attributes aren't used for anything except to decorate an class, method, property, etc. But through reflection you can use them for pretty much what you like, just like ASP.NET MVC does with HttpPost and RequireHttps.

Unfortunately they cannot be OR'ed.

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.