Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing Custom Attribute in C# like ASP.Net MVC Authorize attribute

I like ASP.Net MVC Authorize attribute, I can extend it and build my own logic and decorate my controller with it. BUT,

In my architecture, I have one common service layer(C# Class Library). End user can access my application via ASP.Net MVC web site or via my exposed REST WCF Webservice layer. My asp.net MVC application and REST WCF service layer both in turn access my common service layer.

I want authorization to happen in this common service layer and not in ASP.Net MVC Controller or in my exposed REST Service layer.

Can I create ASP.Net MVC Authorize attribute like thing to decorate my methods in the common C# class library? This attribute will take parameters and will decide if the current user has access to perform that function or not?

Thanks & Regards, Ajay

like image 390
Ajay Avatar asked Jul 29 '09 12:07

Ajay


People also ask

How do I add custom attributes to my framework?

AttributeUsage has a named parameter, AllowMultiple , with which you can make a custom attribute single-use or multiuse. In the following code example, a multiuse attribute is created. In the following code example, multiple attributes of the same type are applied to a class. [Author("P.

What is a custom attribute?

Custom attributes. A custom attribute is a property that you can define to describe assets. Custom attributes extend the meaning of an asset beyond what you can define with the standard attributes. You can create a custom attribute and assign to it a value that is an integer, a range of integers, or a string.

How do I create a custom attribute in .NET core?

Declaring Custom AttributesWe can define an attribute by creating a class. This class should inherit from the Attribute class. Microsoft recommends appending the 'Attribute' suffix to the end of the class's name. After that, each property of our derived class will be a parameter of the desired data type.


1 Answers

What you're looking for can be achieved using AOP library, like PostSharp (http://www.postsharp.org/). It's more complex than using Authorize attribute in mvc, but is still quite simple.

like image 200
maciejkow Avatar answered Sep 22 '22 04:09

maciejkow