按类型访问ServiceStack requestDto对象

Sim*_*mon 3 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;
            }
        }
Run Code Online (Sandbox Code Playgroud)

这行不编译:

 var app = this._appIDs.Apps.Where(x => x.ID == requestDto.AppID).FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)

我是否需要在这里处理反射以访问我的对象或者是否有一些内置于ServiceStack本身的方法?

myt*_*thz 5

将通用功能应用于常见Request DTO时的首选方法是让它们实现相同的接口,例如:

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

public class RequestDto1 : IHasAppId { ... }
public class RequestDto2 : IHasAppId { ... }
Run Code Online (Sandbox Code Playgroud)

然后在你的过滤器中你可以做到:

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

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