如何将位置标头传递给使用命令(API)和查询(odata)控制器的响应

问题描述 投票:0回答:1

场景

嗨,我有用ASP.Net core 2.2编写的命令API控制器。从ControllerBase继承并具有属性ApiController的Controller。我想添加Location标头。我也查询了odata控制器。 Odata版本:7.2.2

Odata代码:

我的Odata控制器:

[ODataRoutePrefix("categories")]
public class ODataCategoriesController : ODataController

Odata采取行动:

[EnableQuery]
[ODataRoute("{id}")]
public async Task<ActionResult<Category>> GetAsync(Guid id)

启动

opt.EnableEndpointRouting = false;
...
app.UseHttpsRedirection();
app.UseMvc(options =>
{
     options.EnableDependencyInjection();
     options.Select().Filter().OrderBy().Count().Expand().MaxTop(100).SkipToken();
     options.MapODataServiceRoute("odata", "api/odata", GetExplicitEdmModel());
});

Tried

我尝试使用CreatedAtAction,但收到:InvalidOperationException:没有路由与提供的值匹配。

在我的POST控制器中:

return CreatedAtAction("Get", "ODataCategories", new { id= categoryResponse.Id }, categoryResponse);

尝试2

我也尝试过手动返回Location标头。但是我收到了:没有标题作为响应。

代码

    [HttpPost]
    [ProducesResponseType((int)HttpStatusCode.Created)]
    [ProducesResponseType((int)HttpStatusCode.BadRequest)]
    public async Task<ActionResult<CreateCategoryResponse>> PostCategory(
        [FromBody]CreateCategoryCommand createCategoryCommand)
    {
        CreateCategoryResponse categoryResponse =
            await _mediator.Send(createCategoryCommand);

        if (categoryResponse == null)
        {
            return BadRequest();
        }

        HttpContext.Response.Headers["Location"] = 
            $"SomeBuiltLocation";
        return Created("", categoryResponse);
    }

摘要

我正在寻找能够使我包含Location标头的解决方案。无论是使用CreatedAt还是手动生成都没有关系。

api asp.net-core header location odata
1个回答
0
投票

也应该能够手动创建。

[HttpPost]
[ProducesResponseType((int)HttpStatusCode.Created)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
public async Task<ActionResult<CreateCategoryResponse>> PostCategory(
    [FromBody]CreateCategoryCommand createCategoryCommand) {
    CreateCategoryResponse categoryResponse =
        await _mediator.Send(createCategoryCommand);

    if (categoryResponse == null) {
        return BadRequest();
    }

    var result = new CreatedResult("SomeBuiltLocation", categoryResponse);
    return result;
}
© www.soinside.com 2019 - 2024. All rights reserved.