【问题标题】:Force Http Get to accept requests either with or without parameters强制 Http Get 接受带参数或不带参数的请求
【发布时间】:2020-05-18 05:17:40
【问题描述】:

考虑控制器:

public class EmployeeController : ApiController
{
    // https://localhost:44344/api/employee/:profession
    [HttpGet]
    [Route("api/employee/{profession}")]
    public HttpResponseMessage Get(String profession)
    {            

        try
        {
            var someBigList = ...
            /// ... do some stuff
            return Request.CreateResponse(HttpStatusCode.OK, someBigList );
        }
        catch (Exception e)
        {
            // error
        }
    }


}

控制器接受以下形式的请求:

https://localhost:44344/api/employee/:profession

但是当我尝试时

https://localhost:44344/api/employee

它没有。

我们如何修复 GET 请求以接受两者?

【问题讨论】:

  • 公共 HttpResponseMessage 获取(字符串职业 = null)
  • @SirRufo:不起作用
  • 提醒自己:不要在一天的第一杯咖啡之前评论/回答;o)

标签: c# .net asp.net-web-api webapi


【解决方案1】:

您可以使用? 标记路由中的可选参数,因此这将是[Route("api/employee/{profession?}")]

或者如果你希望它有一个默认值以防没有给出值,那么使用[Route("api/employee/{profession=value}")]

查看更多来自documentation

【讨论】:

  • 谢谢,不过我得到了:{ "Message": "No HTTP resource was found that matches the request URI 'https://localhost:44344/api/employee'.", "MessageDetail": "No action was found on the controller 'employee' that matches the request." }
【解决方案2】:

如果您想同时允许这两个 URL,那么您必须再添加一个路由。这只会将您的请求路由到操作方法。 现在既然你需要一个参数,那么它应该作为查询字符串的一部分传入请求参数。

新路线应如下所示。

public class EmployeeController : ApiController
{
    // https://localhost:44344/api/employee/:profession
    [HttpGet]
    [Route("api/employee")]
    [Route("api/employee/{profession}")]
    public HttpResponseMessage Get(String profession)
    {            

        try
        {
            var someBigList = ...
            /// ... do some stuff
            return Request.CreateResponse(HttpStatusCode.OK, someBigList );
        }
        catch (Exception e)
        {
            // error
        }
    }


}

【讨论】:

    【解决方案3】:

    根据我的个人经验,如果它不是必需的参数,那么我会从查询中获取值,而不是从路由中获取值。 所以你可以使用[FromQuery] string profession,用法如下:https://localhost:44344/api/employee?profession=developer

    【讨论】:

    • 没有要求这样做,即使它是可能的。如果您使用“应该”,那么请根据应该这样做的方式提供信息。
    • 嗨!感谢您指出了这一点!老实说,这是在 CS 学习期间教给我们的,我认为这是理所当然的,这就是我设计 API 的方式,但经过短暂查找后,我没有找到任何 REST 标准。对不起,误导性的答案,我会尽快编辑!
    猜你喜欢
    • 2015-02-03
    • 1970-01-01
    • 1970-01-01
    • 2013-09-03
    • 1970-01-01
    • 2019-02-08
    • 2015-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多