对通过http发出的所有呼叫返回错误请求

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

我试图找出当通过HTTP连接进行呼叫时如何返回错误请求而不是https。我能弄清楚如何执行此操作的唯一方法是编写中间件并按以下方式检查每个请求:

public class HttpRequestInterceptor
{
    private readonly RequestDelegate _next;

    public HttpRequestInterceptor(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        var scheme = context.Request.Scheme;
        if (scheme.Equals("http", StringComparison.InvariantCultureIgnoreCase))
        {
            context.Response.StatusCode = 400;
            context.Response.ContentType = "application/json";
            await context.Response.WriteAsync("{\"result:\" \"Bad Request\"}", Encoding.UTF8);
            return;
        }

        await _next.Invoke(context);
    }
}

有一个更好的方法吗?也许是通过框架的内置方式?

c# asp.net-core asp.net-core-mvc asp.net-core-2.0 http-redirect
1个回答
2
投票

您可以通过从RequireHttpsAttribute派生来创建自定义过滤器,如this

/// <summary>
/// An authorization filter that closes connections if they are not secure (HTTPS).
/// Be aware that sensitive information sent by the client WILL be visible!
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class RequireHttpsOrCloseAttribute : RequireHttpsAttribute
{
    protected int StatusCode { get; }

    /// <summary>
    /// Return a status result with the given status code when the request does not use HTTPS.
    /// </summary>
    /// <param name="statusCode"></param>
    public RequireHttpsOrCloseAttribute(int statusCode)
    {
        StatusCode = statusCode;
    }

    /// <summary>
    /// Return a 400 Bad Request status code result when the request does not use HTTPS.
    /// </summary>
    public RequireHttpsOrCloseAttribute()
     : this(400)
    {
    }

    /// <summary>
    /// Sets the status result to the appropriate StatusCodeResult specified in the constructor.
    /// The default is 400 Bad Request.
    /// </summary>
    /// <param name="filterContext"></param>
    protected override void HandleNonHttpsRequest(AuthorizationFilterContext filterContext)
    {
        filterContext.Result = new StatusCodeResult(StatusCode);
    }
}

然后,您可以在您的应用程序中全局注册它:

services.AddMvc(opt =>
{
    opt.Filters.Add(new RequireHttpsOrCloseAttribute())
});
© www.soinside.com 2019 - 2024. All rights reserved.