我正在使用 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 本身的方法?
最佳答案
将通用功能应用于通用请求 DTO 时的首选方法是让它们实现相同的接口(interface),例如:
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
...
}
您也可以避免使用接口(interface)并使用反射来代替,但是那样会更慢且可读性差,所以我推荐使用接口(interface)。
关于c# - 按类型访问 ServiceStack requestDto 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19723774/