【问题标题】:How to change the route format of CreatedAtAction in ASP.NET Core 2?如何在 ASP.NET Core 2 中更改 CreatedAtAction 的路由格式?
【发布时间】:2018-08-07 17:33:55
【问题描述】:

在 EF Core 2 中,CreatedAtAction 将参数附加为 api/sample?id=1。如何配置它以返回 api/sample/1?

    [ApiController]
    [Authorize]
    [Route("api/[controller]")]
    public class MyController : ControllerBase
    {
        [HttpGet("{id}")]
        public async Task<IActionResult> Get(int id)
        {
            var entity = await service.GetAsync(id);
            if (entity == null)
                return NotFound(entity);
            return Ok(entity);
        }

        [HttpPut]
        // Other codes are omitted for brevity
        public async Task<IActionResult> Create([FromBody] Entity entity)
        {
            await service.AddAsync(entity);
            await service.SaveAsync();
            return CreatedAtAction(action, new { id = entity.Id }, entity);  
        }    
    }

【问题讨论】:

  • 其实我已经想通了。我一直使用 nameOf(Create) 作为参数。它应该是 nameOf(Get)。谢谢!

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


【解决方案1】:

这是因为动作的路由模板。

很可能是因为默认的基于约定的路由。

这可以通过使用预期路由模板在所需操作上放置属性路由来解决

[Route(api/[controller])]
public class SampleController : Controller {
    //GET api/sample/1
    [HttpGet("{id}")]
    public IActionResult Get(int id) {
        //...
    }

    //POST api/sample
    [HttpPost]
    public IActionResult Post(Sample model) {
        //...

        return CreatedAtAction(nameof(Get), new { id = model.Id }, model);
    }
}

并确保在创建结果时使用正确的操作名称。上面的示例使用了Get 操作,因此在创建的响应中为Location 生成URL 时将使用其路由模板。

【讨论】:

  • 我的 API 已经在使用 api/sample/product/1 模板,并且几乎所有操作都默认使用该模板。唯一返回不同路线的是 CreatedAtAction。
  • @JeonsoftFaceBundy 那么您需要显示导致问题的代码,以便提供更准确的答案。更新原始问题。
  • 我更新了上面的描述。我认为这与您的示例相似。
  • 其实我已经想通了。我一直使用 nameOf(Create) 作为参数。应该是 nameOf(Get)
猜你喜欢
  • 1970-01-01
  • 2016-10-22
  • 1970-01-01
  • 2017-01-08
  • 1970-01-01
  • 2019-05-27
  • 2018-01-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多