Reputation: 6152
I'm using a ServiceStack request filter that I want to inspect one of the properties of the requestDTO parameter. This parameter is strongly typed at runtime but at compile time is a generic object.
The filter will be used on multiple service calls and therefore the requestDTO type will change depending on which has been called. Therefore I cannot perform a specific cast on it. BUT, regardless of type, the requestDTO object will always have a string property named 'AppID'. It is this property I wish to access.
Here's my code (doesn't currently compile):
public override void Execute(ServiceStack.ServiceHost.IHttpRequest req, ServiceStack.ServiceHost.IHttpResponse res, object requestDto)
{
//Check only for non-local requests
if (!req.IsLocal)
{
var app = this._appIDs.Apps.Where(x => x.ID == requestDto.AppID).FirstOrDefault();
var errResponse = DtoUtils.CreateErrorResponse("401", "Unauthorised", null);
var contentType = req.ResponseContentType;
res.WriteToResponse(req, errResponse);
res.EndRequest(); //stops further execution of this request
return;
}
}
This line doesn't compile:
var app = this._appIDs.Apps.Where(x => x.ID == requestDto.AppID).FirstOrDefault();
Do I need to be dealing with reflection here to access my object or is there some way built in to ServiceStack itself?
Upvotes: 3
Views: 139
Reputation: 143399
The preferred approach when applying generic functionality to common Request DTO's is to have them implement the same interface, e.g:
public interface IHasAppId
{
public string AppId { get; set; }
}
public class RequestDto1 : IHasAppId { ... }
public class RequestDto2 : IHasAppId { ... }
Then in your filter you can just do:
var hasAppId = requestDto as IHasAppId;
if (hasAppId != null)
{
//do something with hasAppId.AppId
...
}
You can also avoid the use of an interface and use reflection instead, but that will be slower and less readable, so I recommend interfaces instead.
Upvotes: 5