In ASP.NET Core how do you check if request is local?

前端 未结 6 842
粉色の甜心
粉色の甜心 2020-12-15 03:15

In the regular ASP.NET you could do this in a view to determine if the current request was from localhost:

HttpContext.Current.Request.IsLocal

B

6条回答
  •  眼角桃花
    2020-12-15 03:35

    At the time of writing HttpContext.Connection.IsLocal is now missing from .NET Core.

    Other working solution checks only for a first loopback address (::1 or 127.0.0.1) which might not be adequate.

    I find the solution below useful:

    using Microsoft.AspNetCore.Http;
    using System.Net;
    
    namespace ApiHelpers.Filters
    {
        public static class HttpContextFilters
        {
            public static bool IsLocalRequest(HttpContext context)
            {
                if (context.Connection.RemoteIpAddress.Equals(context.Connection.LocalIpAddress))
                {
                    return true;
                }
                if (IPAddress.IsLoopback(context.Connection.RemoteIpAddress))
                {
                    return true;
                }
                return false;
            }
        }
    }
    

    And the example use case:

    app.UseWhen(HttpContextFilters.IsLocalRequest, configuration => configuration.UseElmPage());
    

提交回复
热议问题