按类型访问ServiceStack requestDto对象

时间:2013-11-01 09:10:18

标签: c# servicestack

我正在使用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本身的方法?

1 个答案:

答案 0 :(得分:5)

将通用功能应用于常见Request 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
    ...
}

您也可以避免使用接口并使用反射,但这会更慢,更不易读,所以我建议使用接口。