using System.Net; using Microsoft.AspNetCore.Antiforgery; using Microsoft.Extensions.DependencyInjection; namespace Microsoft.AspNetCore.Http { /// /// Extensions for the . /// public static class HttpContextExtensions { /// /// Retrieves the antiforgery token. /// /// The web context. /// Name and value of the token. public static (string Name, string Value) GetAntiforgeryToken(this HttpContext httpContext) { var af = httpContext.RequestServices.GetService(); var set = af?.GetAndStoreTokens(httpContext); return (Name: set?.FormFieldName, Value: set?.RequestToken); } /// /// Returns the remote ip address. /// /// The web context. /// The name of the header to resolve the when behind a proxy (Default: X-Forwarded-For). /// The ip address of the client. public static IPAddress GetRemoteIpAddress(this HttpContext httpContext, string headerName = "X-Forwarded-For") { var remote = httpContext.Connection.RemoteIpAddress; string forwardedHeader = httpContext.Request.Headers[headerName].ToString(); if (!string.IsNullOrWhiteSpace(forwardedHeader) && IPAddress.TryParse(forwardedHeader, out var forwarded)) return forwarded; return remote; } /// /// Tries to retrieve the return url. /// /// /// public static string GetReturnUrl(this HttpContext httpContext) { string url = httpContext.Items["OriginalRequest"]?.ToString(); if (string.IsNullOrWhiteSpace(url)) url = httpContext.Request.Query["ReturnUrl"].ToString(); return url; } /// /// Clears a session when available. /// /// The current . public static void ClearSession(this HttpContext httpContext) => httpContext?.Session?.Clear(); } }