我已经创建了一个 .NET Core API 控制器,并且在 POST 方法中,我尝试使用CreatedAtActionResult方法将路由作为 Location Header 包含在我的响应中。[ApiController, Route("v1/[controller]")]public class WidgetController: ControllerBase{ public WidgetController(IWidgetService service) { _service = service; } private readonly IWidgetService _service; [HttpGet("{id}", Name = "GetSingle")] public IActionResult GetSingle(Guid id) { var result = _service.Get(id); return Ok(result); } [HttpPost] public IActionResult Post(WidgetModel model) { var result = _service.Post(model); return result == Guid.Empty ? (IActionResult) BadRequest("No changes saved.") : CreatedAtAction(nameof(GetSingle), new {id = result}, model); }}当我启动应用程序时,POSTman 对 POST 的第一次调用运行没有问题。对象和 Location Header URL 都按预期生成。但是,如果我在代码仍在运行时再次尝试访问该端点,则会出现以下错误:System.InvalidOperationException:1[Microsoft.AspNetCore.Routing.RouteValuesAddress]' has been registered.
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
at Microsoft.AspNetCore.Routing.DefaultLinkGenerator.GetEndpoints[TAddress](TAddress address)
at Microsoft.AspNetCore.Routing.DefaultLinkGenerator.GetPathByAddress[TAddress](HttpContext httpContext, TAddress address, RouteValueDictionary values, RouteValueDictionary ambientValues, Nullable在 Microsoft.AspNetCore.Routing.LinkGeneratorRouteValuesAddressExtensions.GetPathByRouteValues
1 回答
精慕HU
TA贡献1845条经验 获得超8个赞
尝试设置CompatibilityVersion.Version_2_0
或2.1
代替2.2
?
EndpointRouting 在 2.2 的掩护下是一个相当大的变化,您的第 3 方附加组件可能不兼容。
将兼容性设置回 2.1 通常不需要更改控制器中的任何代码,因此成本相当低。
- 1 回答
- 0 关注
- 94 浏览
添加回答
举报
0/150
提交
取消