将端点重定向到 .net core Web api 中的新端点

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

我有一个端点需要弃用,因为需要接收的数据不同。我们的想法是创建一个新的,并且旧的应该重定向到新的,直到客户进行转换。

这是我的试验的一个例子:

    // old method that needs to be redirected 
    [HttpPost("file", Name = nameof(UpooadFileExample))]
    public async Task<ActionResult<Result>> UpooadFileExample(IFormFile file1)
    {
        var contentDisposition = new ContentDisposition
        {
            FileName = "file.xml",
            DispositionType = DispositionTypeNames.Attachment
        };

        var stream = file1.OpenReadStream();

        var file = new FormFile(stream, 0, stream.Length, "file", "file.xml")
        {
            Headers = new HeaderDictionary(
                new Dictionary<string, StringValues> { { "Content-Disposition", contentDisposition.ToString() } })
        };

        // https://procodeguide.com/programming/redirect-a-request-in-aspnet-core/
        return RedirectToActionPermanent(nameof(UpooadFileExampleV2), new { file = file, value_1 = "teste" });
    }

    // new method
    [HttpPost("v2/file", Name = nameof(UpooadFileExampleV2))]
    public async Task<ActionResult<Result>> UpooadFileExampleV2(UploadFile request)
    {
        // do stuff

        return new Result();
    }


    public record UploadFile
    {
        public required IFormFile File { get; set; }
        public  required string Value1 { get; set; }
    }

我正在尝试使用

HTTP 301 MovedPermanently
。 我在 C# 中尝试了一些选项,例如
RedirectToActionPermanent
/
RedirectPermanent
/
RedirectToActionPermanent
,但没有成功。我收到不支持的媒体类型不允许的方法之间的错误消息。

c# .net .net-core
1个回答
0
投票

API 没有像重定向这样的概念 - 原因很简单 - 它主要不是由浏览器调用。

在你的情况下,我会重构一个新的端点并将所有逻辑放入一个方法中,但最好引入一个服务类。这是使用方法方法的示例。

// old method that needs to be redirected 
[HttpPost("file", Name = nameof(UpooadFileExample))]
public async Task<ActionResult<Result>> UpooadFileExample(IFormFile file1)
{
    var contentDisposition = new ContentDisposition
    {
        FileName = "file.xml",
        DispositionType = DispositionTypeNames.Attachment
    };

    var stream = file1.OpenReadStream();

    var file = new FormFile(stream, 0, stream.Length, "file", "file.xml")
    {
        Headers = new HeaderDictionary(
            new Dictionary<string, StringValues> { { "Content-Disposition", contentDisposition.ToString() } })
    };

    var result = await NewEndpoitLogic(new { file = file, value_1 = "teste" });
    return Created(result);
}

// new method
[HttpPost("v2/file", Name = nameof(UpooadFileExampleV2))]
public async Task<ActionResult<Result>> UpooadFileExampleV2(UploadFile request)
{
    var result = await NewEndpointLogic(request);
    return Created(result);
}

private async Task<Result> NewEndpointLogic(UploadFile request)
{
    // do stuff
}
© www.soinside.com 2019 - 2024. All rights reserved.