【问题标题】:How to enable format in routes with ServiceStack in tandem with custom routes?如何使用 ServiceStack 与自定义路由一起启用路由格式?
【发布时间】:2013-06-19 15:43:51
【问题描述】:

我有一些运行良好且匹配 Route 属性的 ServiceStack 服务;但是,Route 属性似乎无法与“自动路由”协同工作。

我想定义路由(例如:/things/{id})并且还可以在 url 中选择格式。目前可以将格式添加为参数。

[Route("/things")]
[Route("/things/{id}")]
public class Things
{
    public string id { get; set; }
}

/api/things
/api/things/{1} (return default format)
/api/json/things
/api/json/things/{1}
/api/xml/things
/api/xml/things/{1}

根据 ServiceStack wiki,URL 中的格式应该“正常工作”。有关如何在 apphost 配置中启用它的任何建议?

【问题讨论】:

    标签: rest servicestack


    【解决方案1】:

    有关路由如何工作的文档,请参阅Routing 上的 wiki 页面,例如如果你想使用预定义的路由,正确的 url 应该是:

    /api/json/reply/Things
    /api/json/reply/things?Id=1
    /api/xml/reply/Things
    /api/xml/reply/things?Id=1
    

    注意:预定义的only使用Request DTO的名称,即它不使用您所有的自定义路由。

    Content Negotiation section on Routing wiki 展示了请求不同内容类型的不同方式。在 ServiceStack (v3.9.54+) 中,您现在可以使用格式 .ext 例如:

    /api/things.json
    /api/things/1.json
    /api/things.xml
    /api/things/1.xml
    

    使用 ?format=ext 参数的替代方法是:

    /api/things?format=json
    /api/things/1?format=json
    /api/things?format=xml
    /api/things/1?format=xml
    

    【讨论】:

    • 太棒了,谢谢!我错过了 wiki 内容协商部分的第二部分,该部分显示支持 .ext(类似于 mvc)。如果可以的话,还有 2 个小的后续问题:(1)如何移动 ext 位置(即:/api.ext/)。不是破坏交易,但可能在 mvc 路由中。 (2) 一些 ID 是字符串,有时带有点 (bob.dole)。发送 bob.dole.json 就像一个魅力。怎么样?
    • 1) 它只在 pathInfo 的末尾起作用,而不是在中间。 2) 它只查看最终扩展名,并且只有在扩展名是内置或用户注册的 Content-Type 时才会生效。
    • 感谢您及时跟进。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-08
    • 1970-01-01
    • 2013-06-11
    • 2021-09-02
    • 2017-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多