Lookup current service operation?

I am writing a request filter that must be called before any RequestFilterAttributes.
It looks like this: public static Action<IRequest, IResponse, object> MyFilter() { my code... }

I am going to add this filter to the AppHost.GlobalFilters in AppHost.Configure().

Within this code, I need to figure out what attributes (actually ResponseFilterAttributes) that are declared upon the specific service operation that would be called in the current request.

For example, my service operations look like this:

public object Get(MyDto dto)

my attribute looks as expected:

public class MyAttribute : ResponseFilterAttribute
    public MyAttribute(string value)
        Value = value;

    public string MyValue { get;set; }

From the code in my filter, I need to access the declared values in that attribute. In other words, I need to get the value of the MyValue property of the attribute above.

Is it possible?

The normal approach is to use the IRequest.Items Dictionary to send any info throughout different handlers in the Request Pipeline. So you’d typically populate an item in the Request Filter that the Response Filter further down the Request Pipeline would then be able to access.

Trying to access information about the Response Filter from the Request Filter would therefore be backwards. IMO a cleaner declarative approach would be for the Request DTO to implement an interface like IHasValue which would return the value from a method like GetValue(). That way the Request Filter can cast check the dto into IHasValue or more succinctly use a Type Request Filter, e.g:

RegisterTypedRequestFilter<IHasValue>((req, res, dto) => {
    var theValue = dto.GetValue();

Otherwise all information about the Request and Response DTO’s are accessible from HostContext.Metadata which you can access from a request DTO with:

var operation = HostContext.Metadata.GetOperation(typeof(MyDto));

This does let you access the RequestFilterAttributes and ResponseFilterAttributes that are defined on the Request DTO or Service class but not the Action Filter attributes which are fused together within the execution context of a service. So ServiceStack doesn’t offer a public API to access it, if you really wanted it you would need to access it manually via reflection yourself, e.g:

var requestType = typeof(MyDto);
var op = HostContext.Metadata.GetOperation(requestType);
var mi = op.ServiceType
    .FirstOrDefault(x => x.GetParameters().Length == 1 
        && x.GetParameters()[0].ParameterType == requestType
        && x.Name == "Get");

var attr = mi.FirstAttribute<MyAttribute>();
attr.Value //= avalue

OK, thanks for this.

Let me investigate the HostContext you suggest.

I presume then, can you confirm? that the ctor of my ResponseFilterAttribute will be called before my global request filter runs?


Yeah but that’s a .NET thing, i.e. attribute constructors are called when you try to access the attribute via reflection.