Reputation: 61616
I have a pretty standard .net core 2 WebApi project. I want to add an attribute on a method that will kick off when the action is called.
In the pseudo code below whenever someone posts to the foo
action, I'd like to log the body of the POST. To that end I add the [LogBody]
attribute. But I don't know how to actually kick off a method in the attribute.
class SomeController: Controller {
[HttpPost]
[LogBody]
public void foo([FromBody] SomeObj obj) {
return View(obj);
}
}
class LogBodyAttribute: Attribute {
void LogIt() {
string methodName = getMethodName();
string body = new StreamReader(Request.Body, Encoding.UTF8).ReadToEnd();
SaveData(methodName, body);
}
}
P.S. I know I can do this with PostSharp, but I'd rather not.
Upvotes: 0
Views: 1114
Reputation: 112392
The attributes provide a static meta-data that is included into the compiled code. This information can be queried at run-time and used to perform logic; however, the attribute by itself cannot trigger an action.
Given an object, you can get the attribute like this:
Type type = controller.GetType();
var myAttribute = type
.GetMethod(methodName)
.GetCustomAttributes(true)
.OfType<MyAttribute>()
.FirstOrDefault();
The Boolean argument to GetCustomAttributes
indicates whether inherited attributes must be returned.
Maybe what you are looking for is Aspect-oriented programming AOP. This allows you to inject code into methods and properties in a post compilation process. Attributes can be used to include or exclude methods. There are different AOP products available for C#.
Yet another approach is to use the Decorator pattern. A decorator is a wrapper class providing the same API than the wrapped class and allows to add behavior to the methods and properties of the wrappee. Used together with an inversion of control (IoC) Container or with the Factory method pattern, behavior can automatically be injected.
Upvotes: 2
Reputation: 1187
It can be done, but it's not easy - and the immediate answer to your question involves reflection and code injection stuff. Here is an SO question that might help you do what you want: C# Attribute to trigger an event on invoking a method
Upvotes: 2