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 current .
/// 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 current .
/// 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")
{
string forwardedHeader = httpContext.Request.Headers[headerName].ToString();
if (!string.IsNullOrWhiteSpace(forwardedHeader) && IPAddress.TryParse(forwardedHeader, out var forwarded))
return forwarded;
return httpContext.Connection.RemoteIpAddress;
}
///
/// Returns whether the request was made locally.
///
/// The current .
/// The name of the header to resolve the when behind a proxy (Default: X-Forwarded-For).
///
public static bool IsLocalRequest(this HttpContext httpContext, string headerName = "X-Forwarded-For")
{
var remoteIpAddress = httpContext.GetRemoteIpAddress(headerName);
return httpContext.Connection.LocalIpAddress.Equals(remoteIpAddress);
}
///
/// Tries to retrieve the return url.
///
/// The current .
///
public static string GetReturnUrl(this HttpContext httpContext)
{
if (httpContext.Items.ContainsKey("OriginalRequest"))
return httpContext.Items["OriginalRequest"].ToString();
if (httpContext.Request.Query.ContainsKey("ReturnUrl"))
return httpContext.Request.Query["ReturnUrl"].ToString();
return null;
}
///
/// Clears a session when available.
///
/// The current .
public static void ClearSession(this HttpContext httpContext)
=> httpContext.Session?.Clear();
}
}