asp.net-corehttprequesthttp-protocols

Restrict HTTP request based on HTTP Protocol in ASP.NET Core


I want to restrict the HTTP request based on the HTTP request protocol lower than 2.0 in ASP.NET Core. Can we add any policy in the startup.cs file that will restrict the HTTP request based on the HTTP protocol?

Thanks


Solution

  • You can use middleware to get the protocol of the current request, and then judge whether it is lower than HTTP/2. For example:

    app.Use(async (context, next) =>
    {
        var Protocol = context.Request.Protocol;
        if (float.Parse(Protocol.Remove(0,Protocol.Length - 1)) < 2)
        {
            //You can use other methods to restrict requests
            //If using redirection will initiate another request, please make sure that the protocol used by this request is not lower than HTTP/2
            context.Response.Redirect("/Home/Error");
        }          
        await next.Invoke();
    });