【问题标题】:How can I have two routes that use the same Method using C# WebAPI 2如何使用 C# WebAPI 2 拥有两条使用相同方法的路由
【发布时间】:2016-01-03 03:19:57
【问题描述】:

我正在使用 C# 和 Web API 2 项目。我想要一个控制器,它的功能包含同一方法的两条可能的路线。如果未设置大小,我希望它传递 null。到目前为止,我已经尝试过:

public class PController : ApiController
{
    [Route("~/personphoto/{id:Guid}")]
    [Route("~/personphoto/{id:Guid}/sizes/{string:size}")]
    [AllowHeaderFilter(HttpMethodFlag.Get)]
    public IHttpActionResult GetPhoto(Guid id, string size)
    {
        // Do Something
    }
}

这可能吗?

【问题讨论】:

  • [Route("~/personphoto/{id:Guid}/sizes/{string:size}")] 路由有什么问题?如果您不想传递大小,则将其传递为 null。您是否有任何特定原因要创建两条路线。
  • 我想创建一个分配默认尺寸的路线,因此您不必将尺寸/{size}放入

标签: c# c#-4.0 routes asp.net-web-api2


【解决方案1】:

我相信这就是您要找的:

[Route("~/personphoto/{id:Guid}/{sizes?}/{size?}")]
public IHttpActionResult GetPhoto(Guid id, string sizes = "", string size = "")

【讨论】:

  • 我猜“sizes”是字符串文字,而不是参数,在 op 情况下。
猜你喜欢
  • 2020-03-22
  • 2019-03-11
  • 1970-01-01
  • 2016-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-25
相关资源
最近更新 更多