如何使用ServiceStack将href转换为RequestDto?

时间:2013-07-30 10:43:09

标签: rest servicestack hateoas

我正在构建一个支持链接资源扩展的ReST API,我无法弄清楚如何使用ServiceStack的本机绑定功能将URL转换为填充的“请求DTO”对象。

例如,假设我的API允许您使用此请求检索有关乐队的信息:

GET /bands/123

< 200 OK
< Content-Type: application/json
{
    "href": "/bands/123",
    "name": "Van Halen",
    "genre": "Rock",
    "albums" {
        "href" : "/bands/1/albums",
    }
}

如果你想扩展乐队的专辑列表,你可以这样做:

GET /bands/1?expand=albums

< 200 OK
< Content-Type: application/json
{
    "href": "/bands/123",
    "name": "Van Halen",
    "genre": "Rock",
    "albums" {
        "href" : "/bands/1/albums",
        "items": [
            { "href" : "/bands/1/albums/17892" },
            { "href" : "/bands/1/albums/28971" }
        ]
    }
}

我正在使用ServiceStack,我想通过重用现有的服务方法来执行此内联扩展。

我的ServiceStack响应DTO看起来像这样:

public class BandDto {
    public string Href { get; set; }
    public string Name { get; set; }
    public AlbumListDto Albums { get; set; }
}

public class AlbumListDto {
    public string Href { get; set; }
    public IList<AlbumDto> Items { get; set;}
}

public class AlbumDto {
    public string Href { get; set; }
    public string Name { get; set; }
    public int ReleaseYear { get; set; }
}

我的ServiceStack请求/路由对象是这样的:

[Route("/bands/{BandId}", "GET")]
public class Band : IReturn<BandDto> { 
    public string Expand { get; set; }
    public int BandId { get; set; }
}

[Route("/bands/{BandId}/albums", "GET")]
public class BandAlbums : IReturn<AlbumListDto> { 
    public int BandId { get; set; }
}

并且处理请求的实际服务是这样的:

public class BandAlbumService : Service {
    public object Get(BandAlbums request) {
         return(musicDb.GetAlbumsByBand(request.BandId));
    }
}


public class BandService : Service {

    private IMusicDatabase db;
    private BandAlbumService bandAlbumService;

    public BandService(IMusicDatabase musicDb, BandAlbumService bandAlbumService) {
        this.db = musicDb;
        this.bandAlbumService = bandAlbumService;
    }

    public object Get(Band request) {
        var result = musicDb.GetBand(request.BandId);

        if (request.Expand.Contains("albums")) {
            // OK, I already have the string /bands/123/albums
            // How do I translate this into a BandAlbums object
            // so I can just invoke BandAlbumService.Get(albums)

            var albumsRequest = Translate(result.Albums.Href);
            result.Albums = bandAlbumService.Get(albumsRequest);
    }
}

在上面的示例中,假设我已将字符串/bands/123/albums计算为Van Halen专辑列表的HREF。

我现在如何使用ServiceStack的内置绑定功能将字符串/bands/123/albums转换为可以直接传递到BandAlbumService的BandAlbums'请求'对象,获取填充的BandAlbumsDto对象并将其包含在我的回应对象?

(是的,我知道这可能不是最小化数据库命中率的最佳方法。我稍后会担心这一点。)

1 个答案:

答案 0 :(得分:2)

RestPath应该能够帮助您:

我认为这应该有效:

var restPath = EndpointHostConfig.Instance.Metadata.Routes.RestPaths.Single(x => x.RequestType == typeof(AlbumRequest));
var request = restPath.CreateRequest("/bands/123/albums")