【问题标题】:Response format specification in ASP.NET MVC 3 RoutesASP.NET MVC 3 Routes 中的响应格式规范
【发布时间】:2011-04-15 19:11:01
【问题描述】:

我正在为网站创建 API。我正在使用 ASP.Net MVC 3,并且正在尝试创建支持可选 .format 参数的路由。所以客户端应用程序可以请求 /user/post.json、/user/posts.xml 或只是 /users/posts 我能够使用以下路线使 .json 或 .xml 结束 url 工作:

    routes.MapRoute( _
        "no_params", _
        "{controller}/{action}.{format}", _
        New With {.action = "Index", .format = UrlParameter.Optional} _
    )

但如果没有 .format 参数 (/user/posts),我无法使 url 一起工作。谁能帮我举个例子?

谢谢!

【问题讨论】:

  • 你用的是什么版本的iis?
  • .可能会在这里引起您的问题。为什么不创建另一个没有 .并将其添加到 no_params 路由之后。这样,如果一个带有 .到达它将由 no_params 路由处理。

标签: asp.net asp.net-mvc vb.net asp.net-mvc-3 asp.net-mvc-routing


【解决方案1】:

首先我会说客户端可以使用'content-type'而不是url来指定类型:)

但要使其正常工作,您需要注册另一个没有格式的路由,因为使用 /user/posts 不包含句点 (.) 它无法匹配您指定的路由。

routes.MapRoute("no_params_no_format", "{controller}/{action}", _

    New With {.action = "Index" } _
)

HTH

【讨论】:

    【解决方案2】:

    只需删除点:

    routes.MapRoute( _
        "no_params", _
        "{controller}/{action}{format}", _
        New With {.action = "Index", .format = UrlParameter.Optional}, _
        New With {.format = "(\.json|\.xml)?"} _
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-29
      • 1970-01-01
      • 1970-01-01
      • 2017-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多