2013-11-01 36 views
3

我正在使用ServiceStack请求过滤器,我想要检查requestDTO参数的其中一个属性。该参数在运行时强类型化,但在编译时是一个通用对象。按类型访问ServiceStack requestDto对象

该过滤器将用于多个服务调用,因此requestDTO类型将根据调用的内容而改变。因此我无法对它进行特定的演员表演。但是,不管类型如何,requestDTO对象将始终有一个名为“AppID”的字符串属性。这是我希望访问的这个属性。

这里是我的代码(目前不编译):

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; 
      } 
     } 

此行不会编译:

var app = this._appIDs.Apps.Where(x => x.ID == requestDto.AppID).FirstOrDefault(); 

我需要与反思这里要处理访问我的对象或有没有内置到ServiceStack本身?

回答

5

应用通用的功能,以共同请求DTO的时候首选的方法是让他们实现相同的接口,如:

public interface IHasAppId 
{ 
    public string AppId { get; set; } 
} 

public class RequestDto1 : IHasAppId { ... } 
public class RequestDto2 : IHasAppId { ... } 

然后在你的过滤器,你可以这样做:

var hasAppId = requestDto as IHasAppId; 
if (hasAppId != null) 
{ 
    //do something with hasAppId.AppId 
    ... 
} 

你也可以避免使用接口并使用反射来代替,但这样会更慢,更不可读,所以我推荐使用接口。

+0

Gargh,当然。他们已经实施了适当的界面,我很愚蠢。再次感谢。 – Simon