我们正在将 Web API 升级到 .Net Core。该 API 是一个员工 API,具有员工搜索和 GET 端点,如下所示:
GET /employees/{id}
GET /employees
对于 Get 端点,当前以下两个调用均有效:
https://example.com/employees/001
https://example.com/employees/{id}?id=001
将代码升级到.Net Core 6.0后,只有以下调用可以工作:
https://example.com/employees/001
查询字符串中带有 id 的其他调用不起作用。有没有办法让这两个调用都在 .Net Core 中工作?
这就是您定义路线的全部方式。如果您将参数放入路由中,例如 /employees/001,它将查找该路径以确定要调用哪个函数。例如,我设置了 2 条调用 2 个函数的路由:
[Route("Stuff/{id}")]
public IActionResult StuffWithIDInPath(int id)
{
ViewData["idVal"] = id;
return View("SomeStuff");
}
[Route("Stuff")]
public IActionResult StuffWithIDInQS(int id)
{
ViewData["idVal"] = id;
return View("SomeStuff");
}
当我去某物/东西/37时,第一条路线就被击中了
第二个函数在路由中没有参数,但它也是函数的参数,所以它知道如果它出现就去找它:
但也许您想要一个函数来处理这两种情况,如果您只是为同一函数正确定义路由,则可以同时执行这两个操作。
[Route("Stuff/{id}")]
[Route("Stuff")]
public IActionResult StuffWithIDEitherPlace(int id)
{
ViewData["idVal"] = id;
return View("SomeStuff");
}
在这种情况下,任一 URL 将转到该函数,处理路由中的参数或作为查询字符串。
你的操作路由属性应该有 id 作为可选参数
[HttpGet("~/employees/{id?}")]
public IActionResult Get(int? id)
或者如果控制者是员工
public class Employees : ApiController
..........
[HttpGet("id?}")]
public IActionResult Get(int? id)
这很有效,因为我最终像这样合并了 .NET Framework Get() 和 Get(string lat, string lng)。如果我从头开始创建它,我不会这样做,但我有一个 IOS 应用程序,在我将 API 迁移到 .NET Core 后需要更新。
// Get All Restaurants OR Get By Latitude/Longitude
[HttpGet]
public async Task<ActionResult<IEnumerable<LocationListViewModel>>> Get(string lat = "", string lng = "")
{
if (string.IsNullOrEmpty(lat) && string.IsNullOrEmpty(lng))
{
return await _locationService.GetRestaurantsAsync();
}
else
{
return await _locationService.GetRestaurantsByLatLngAsync(lat, lng);
}
}