在不干扰现有合约的情况下向 Web API 操作方法添加新参数

Adding new parameter to a web API action method without disturbing the existing contract

我的 web api 2.0 项目中已经编写了一个操作方法。我想在不影响现有合同的情况下添加一个新参数。最好的方法是什么?感谢对此的任何最佳实践提示 :)

这是我打算做的代码示例:

现有代码:

[Route("{myId}",Name="MyId")]
Public IHttpActionResult Get(String myId)
{
  //Some more code here
}

Url: http://localhost:8888/webapi/1111

期望执行如下操作:

//I want to keep the route name same for backwards compatibility.
[Route("{myId}/{myName}",Name="MyId")]
Public IHttpActionResult Get(String myId,string? myName)
{
  //Some more code here
}

Url: http://localhost:8888/webapi/1111/John 上面提到的 Url 正确地命中了方法,但是我从来没有得到第二个参数 (myName) 填充了 John.

感谢大家为此提供的帮助。 斯里

String 是引用类型,因此您无需将其设为可空,它已经可以了。去除那个 '?'并从属性中删除名称。然后会发生什么?

在您的示例中,您将 myName 作为 string?,这是不允许的:

The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable'

已创建测试控制器来实施您的操作

[RoutePrefix("webapi")]
public class TestsController : ApiController {
    [HttpGet]
    [Route("{myId}/{myName}", Name = "MyId")]
    public IHttpActionResult Get(string myId, string myName) {
        //Some code to show the values of the parameters
        return Ok(new { myId = myId, myName = myName });
    }
}

当使用 webapi/1111/John 进行测试时,返回以下响应

{"myId":"1111","myName":"John"}

其中确实包括 MyName 的值 John

如果尝试反向 uri webapi/1111,将返回 NotFound 响应,因为模板与新操作不匹配。

要解决此问题,您需要将 myName 参数设为可选。要了解有关该检查的更多信息

Optional URI Parameters and Default Values

新路线看起来像

//NOTICE THE `?` ON THE {myName} TEMPLATE
[Route("{myId}/{myName?}", Name = "MyId")]
public IHttpActionResult Get(string myId, string myName = null) {...}

您会注意到 myName 在路由 {myId}/{myName?} 和操作参数 (string myId, string myName = null)

中是可选的

现在,当使用 webapi/1111 进行测试时,会返回以下响应

{"myId":"1111","myName":null}

为了向后兼容,这将符合您的预期结果。