【问题标题】:ASP.Net Core Api middleware to end request by calling a controller actionASP.Net Core Api 中间件通过调用控制器操作来结束请求
【发布时间】:2020-10-16 17:43:00
【问题描述】:

服务器:ASP.net Core Web API

客户端:WinForms 应用程序使用 Refit 并随每个请求发送其版本(作为标头)

服务器如何检查客户端请求的版本,如果错误则通过调用控制器操作 VersionError 进行回复?

此代码不会结束请求:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseRouting();
    app.UseAuthorization();

    app.Use(async (context, next) =>
    {
        foreach (var header in context.Request.Headers)
        {
            Console.WriteLine($"{context.Request.Path} : {header.Key}={header.Value}");

            if (header.Key == "CLIENT-VERSION" && header.Value != "5")
            {
                context.Request.Method = "GET";
                context.Request.Path = "/api/Error/VersionError";
            }
        }

        await next();
    });

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

[ApiController]
[Route("api/[controller]/[action]")]
public class ErrorController : ControllerBase
{
    [HttpGet]
    public Message<string> VersionError()
    {
        var reply = new Message<string>(errorMessage: "version error");
        return reply;
    }
}

【问题讨论】:

    标签: c# asp.net-web-api asp.net-core-middleware


    【解决方案1】:

    尝试替换:

    context.Request.Method = "GET";
    context.Request.Path = "/api/Error/VersionError";
    

    与:

    context.Response.Redirect("/api/Error/VersionError");
    return;
    

    【讨论】:

    • Refit.ApiException:响应状态码不表示成功:302(找到)。
    【解决方案2】:

    您不应该在中间件中这样做,而是应该使用全局Action Filter

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-02
      • 2019-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-03
      相关资源
      最近更新 更多