Click here to Skip to main content
15,919,613 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

I want to write a simple attribute (in attribute class) to do the following:
1. Get a user name.
2. Example (if the user name was equals "admin" go to index) do else redirect to login page.

-- Thanks in advance.

C#
[Permission("Admin")]
private Actionresult Index()
{
//do something
}
.....
Public class PermissionAttribute:Attribute
{
public PermissionAttribute(string Username)
{
//What must I do??
}
}
Posted
Updated 1-Mar-12 13:42pm
v6
Comments
Herman<T>.Instance 28-Feb-12 5:12am    
is this homework?
what have you tried?
[no name] 28-Feb-12 5:25am    
this is not home work
i want to write a simple Authorized attribute
Herman<T>.Instance 28-Feb-12 5:27am    
good you have improved your question!
[no name] 28-Feb-12 5:28am    
do you have a solution?

In your attribute class PermissionAttribute there is not much more to do than to store the users name. An attibute is just a method of decorating classes or methods with additional information it does not do any actual work. It can't really do any actual work as the attribute does not know anything of the class or method it decorates. If you want some introductory material regarding attributes please refer to the following links:

Introduction to Attributes[^]
- Using Attributes[^]
- Attribute Targets[^]
- Global Attributes[^]
- Creating Custom Attributes[^]
- Retrieving Information[^]

The last item is of special interest to you. In your code you need to find out if a certain class or method is decorated with the attribute(s) you generated. Your code then decides what to do when such an attribute is found and takes the appropriate actions. Data contracts and operation contracts are examples of using attributes in the .NET Framework.

Regards,

Manfred
 
Share this answer
 
Comments
[no name] 28-Feb-12 6:10am    
thank but do you have an example?
how can do some thing like Authorized attribute?
Manfred Rudolf Bihy 28-Feb-12 6:26am    
There is an example in the section Retrieving Information that uses an AuthorAttribute which looks pretty analogous to your PermissionAttribute. Please read the sections I refered you to for copious information.
Since you're using MVC you should use the MVC AuthorizeAttribute Class[^] instate of write you're own. All you try to achieve is build in MVC for you :-).

Regards
Piet
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900