c# - 按类型访问 ServiceStack requestDto 对象

标签 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 本身的方法?

最佳答案

将通用功能应用于通用请求 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/

相关文章:

servicestack - 使用 ServiceStack 和 ORMLite SQLServer 进行审计跟踪

json - 使用 ServiceStack 提供带有 .json 文件扩展名的物理 JSON 文件

c# - 如何在 DependencyProperty 中调用按钮单击或事件

c# - ActiveX 控件名称不可用

c# - 如何使用客户端 Windows 凭据连接到 Web 中的 SQL Server 数据库

servicestack - 使用 ServiceStack 为根路径 '/' 创建路由

c# - 在 Linux/Mono 上运行 ServiceStack 的最佳方式是什么?

c# - 身份验证失败时的 ServiceStack 自定义响应

c# - 日历插件

c# - 管理源代码的方法