2

我正在使用服务堆栈中的剃须刀功能。我有一个适用于我的响应 DTO 的剃刀 cshtml 视图。

我需要从 razor 视图中的请求 DTO 访问一些值,这些值已从 REST 路由的某些字段中填充,因此我可以构造一个 url 以放入响应 html 页面并标记一些表单标签。

反正有这样做吗?我不想仅为这个 html 视图将请求 DTO 中的属性复制到响应 DTO 中。因为我正在尝试模拟另一个产品的现有 REST 服务,所以我不想仅为 html 视图发出额外的数据。

例如 http://localhost/rest/{Name}/details/{Id}

例如

    @inherits ViewPage<DetailsResponse>
   @{

        ViewBag.Title = "todo title";
        Layout = "HtmlReport";
   }

这需要来自请求 dto NOT @Model

<a href="/rest/@Model.Name">link to user</a>
<a href="/rest/@Model.Name/details/@Model.Id">link to user details</a>

4

1 回答 1

4

如果您想访问Request DTO它需要通过将请求添加到响应 DTO(您不想这样做)来引用它,所以另一个选择是将它添加到IHttpRequest.Items字典中,这是传递的首选方式您的过滤器和服务之间的数据。

public class MyService : Service {
    public object Any(MyRequest request) {
        base.Request.Items["RequestDto"] = request;
        return MyResponse { ... };
    }
}

那么在你看来:

@{
   var myRequest = (MyRequest)base.Request.Items["RequestDto"];
}

在请求过滤器中包装可重用功能

如果您发现需要在视图中访问请求 DTO 很多,而不是在每个服务中手动分配它,您可以创建一个请求过滤器属性,或者如果您希望它一直在全局请求过滤器中分配。

public class SetRequestDtoAttribute : RequestFilterAttribute {
    public override void Execute(
        IHttpRequest req, IHttpResponse res, object requestDto)
    {
        req.Items["RequestDto"] = requestDto;
    }
}

[SetRequestDto]然后,您可以通过在 Action、Service、Request DTO 或基类的不同粒度级别上装饰属性来添加此行为。

于 2012-11-07T07:41:03.060 回答