How to find Service from ServiceStack RequestFilter

此生再无相见时 提交于 2019-12-18 05:23:13

问题


I'm trying to implement a RequestFilter that conditionally executes, based on information in the Service that would get invoked. I'd like to make the RequestFilter find the Service, look at it for a method/interface/attribute, and conditionally do its work based on that.

I'm aware that you can declare a RequestFilterAttribute on the Service, but I couldn't figure out a good way to make it conditional. I wanted to pass a delegate/lambda into the attribute, but C# doesn't allow that. I could have plugged in a Type or type name into there, allowing the RequestFilterAttribute to find the Service class/method, but that seemed prone to copy/paste errors.

So I'm left with wanting some way for a RequestFilter or RequestFilterAttribute to know about the Service it's acting on (or declared on) and then wanting to look up a method inside that Service that would provide the logic needed to enable/disable the filter's code. I couldn't tell if some feature of the IoC container offered this, or if there is some other way to do it, or not.

And then, based on how the filter executes, it might need to return its own data, blocking the Service from actually executing. Is this possible? (Is this the answer for that?)


回答1:


This seems to be the key:

var serviceType = EndpointHost.Metadata.GetServiceTypeByRequest(requestDto.GetType());

This returns the type of the service that will handle the request. It's not an instance (but I am doubtful a service instance has even been created yet) so to do conditional logic I had to define a static method and then look it up. I used reflection to find a method declaring a special attribute, and will need to optimize that for best performance.

From there I can conditionally determine whether to run some logic. I can also bypass calling the service if I like and return a success response as follows:

var successResponse = DtoUtils.CreateSuccessResponse(successMessage);
var responseDto = DtoUtils.CreateResponseDto(requestDto, successResponse);
var contentType = req.ResponseContentType;
res.ContentType = contentType;
res.WriteToResponse(req, responseDto);
// this is the proper way to close the request; you can use Close() but it won't write out global headers
res.EndServiceStackRequest();
return;

Or I can create an error response, or just return from the RequestFilter and let the service execute normally.



来源:https://stackoverflow.com/questions/15317540/how-to-find-service-from-servicestack-requestfilter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!