如何在C#中编写属性 [英] How to write an Attribute in C#

查看:66
本文介绍了如何在C#中编写属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我想编写一个简单的属性(在属性类中)以执行以下操作:
1.获取用户名.
2.示例(如果用户名等于"admin",请转到索引),否则将重定向到登录页面.

-预先感谢.

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.

[Permission("Admin")]
private Actionresult Index()
{
//do something
}
.....
Public class PermissionAttribute:Attribute
{
public PermissionAttribute(string Username)
{
//What must I do??
}
}

推荐答案

在您的属性类PermissionAttribute中,除了存储用户名外,没有其他要做的事情.装扮只是用附加信息修饰类或方法的一种方法,它没有任何实际作用.它不能真正做任何实际的工作,因为属性不知道它装饰的类或方法的任何信息.如果您需要一些有关属性的入门资料,请参考以下链接:

属性简介 [使用属性 [属性目标 [全局属性 [创建自定义属性 [检索信息 [
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


由于您正在使用MVC,因此应使用MVC
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


这篇关于如何在C#中编写属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆