首页 > 解决方案 > ASP.NET Core:匹配路由,一个有body,一个没有

问题描述

我有DELETE一条看起来像这样的路线:

[HttpDelete("{id}")]
public async Task<StatusCodeResult> DeleteService(string id)
{
    return await _repo.DeleteServiceAsync(id);
}

我还需要[FromBody]在这条路线上支持一个参数,它是这样的:

[HttpDelete("{id}")]
public async Task<StatusCodeResult> DeleteService([FromBody] ServiceEntity service, string id)
{
    if(service == null)
        return await _repo.DeleteServiceAsync(id);
    else
        return await _repo.DeleteServiceWithEntityAsync(id, service);
}

但是,由于AllowEmptyInputInBodyModelBinding,这不起作用,我不想将其设置为 true;在每个其他路由/端点中,都需要默认行为 , AllowEmptyInputInBodyModelBinding == false

我可以有两条不同的路由,一条带有 body 参数,一条不带,但这会产生匹配的路由,并且两个端点都没有命中:

[HttpDelete("{id}")]
public async Task<StatusCodeResult> DeleteService(string id)
{
    return await _repo.DeleteServiceAsync(id);
}

[HttpDelete("{id}")]
public async Task<StatusCodeResult> DeleteServiceWithEntity([FromBody] ServiceEntity service, string id)
{
    return await _repo.DeleteServiceWithEntityAsync(id, service);
}

获得我想要的行为的最佳方法是什么?我无法添加单独的端点,因为我需要与现有 API 保持一致。

标签: c#asp.net-coreasp.net-core-webapi

解决方案


推荐阅读