IUrlHelper.Action()调用Delete()操作方法返回null问题排查
问题原因与解决方案
这个问题的核心在于**Url.Action在生成URL时,会默认使用当前请求的HTTP方法来筛选匹配的Action路由**。
你现在是在Get()这个GET请求的Action里调用Url.Action,框架会自动用GET方法去查找目标Action的路由。但你的Delete()方法标记了[HttpDelete],只接受DELETE请求,框架找不到符合GET方法的Delete Action路由,自然就返回null了。而带id的Get()方法是GET请求,所以能匹配到,生成URL正常。
解决方案1:给Delete路由命名,用Url.RouteUrl生成
给Delete方法添加路由名称,直接通过名称匹配路由,不受当前请求HTTP方法的限制:
[HttpDelete("{id}", Name = "DeleteWeatherForecast")] public IActionResult Delete([FromRoute] int id) { return NoContent(); }
然后修改生成URL的代码:
Delete = Url.RouteUrl("DeleteWeatherForecast", new { version = "2", id = 1 }, "https");
解决方案2:使用LinkGenerator(推荐,更灵活)
ASP.NET Core的LinkGenerator组件不依赖当前请求的HTTP方法,能更精准地生成指定Action的URL。首先在控制器中注入LinkGenerator:
private readonly LinkGenerator _linkGenerator; public WeatherForecastController(LinkGenerator linkGenerator) { _linkGenerator = linkGenerator; }
然后修改生成Delete URL的代码:
Delete = _linkGenerator.GetUriByAction( HttpContext, action: nameof(WeatherForecastController.Delete), controller: "WeatherForecast", values: new { version = "2", id = 1 }, scheme: "https");
解决方案3:显式指定HTTP方法
如果你不想引入LinkGenerator,也可以通过RouteValueDictionary传入httpMethod参数,强制Url.Action匹配DELETE方法的路由:
Delete = Url.Action( nameof(WeatherForecastController.Delete), "WeatherForecast", new RouteValueDictionary { { "id", 1 }, { "version", "2" }, { "httpMethod", HttpMethod.Delete.Method } }, "https");
以上任意一种方案都能让Delete字段正常生成预期的URL。
内容的提问来源于stack exchange,提问作者Adrian at DMI
相关产品推荐
相关产品推荐

