1
0
Files
common/AMWD.Common.AspNetCore/Extensions/HttpContextExtensions.cs

76 lines
2.8 KiB
C#

using System.Net;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.Extensions.DependencyInjection;
namespace Microsoft.AspNetCore.Http
{
/// <summary>
/// Extensions for the <see cref="HttpContext"/>.
/// </summary>
public static class HttpContextExtensions
{
/// <summary>
/// Retrieves the antiforgery token.
/// </summary>
/// <param name="httpContext">The current <see cref="HttpContext"/>.</param>
/// <returns>Name and value of the token.</returns>
public static (string Name, string Value) GetAntiforgeryToken(this HttpContext httpContext)
{
var af = httpContext.RequestServices.GetService<IAntiforgery>();
var set = af?.GetAndStoreTokens(httpContext);
return (Name: set?.FormFieldName, Value: set?.RequestToken);
}
/// <summary>
/// Returns the remote ip address.
/// </summary>
/// <param name="httpContext">The current <see cref="HttpContext"/>.</param>
/// <param name="headerName">The name of the header to resolve the <see cref="IPAddress"/> when behind a proxy (Default: X-Forwarded-For).</param>
/// <returns>The ip address of the client.</returns>
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;
}
/// <summary>
/// Returns whether the request was made locally.
/// </summary>
/// <param name="httpContext">The current <see cref="HttpContext"/>.</param>
/// <param name="headerName">The name of the header to resolve the <see cref="IPAddress"/> when behind a proxy (Default: X-Forwarded-For).</param>
/// <returns></returns>
public static bool IsLocalRequest(this HttpContext httpContext, string headerName = "X-Forwarded-For")
{
var remoteIpAddress = httpContext.GetRemoteIpAddress(headerName);
return httpContext.Connection.LocalIpAddress.Equals(remoteIpAddress);
}
/// <summary>
/// Tries to retrieve the return url.
/// </summary>
/// <param name="httpContext">The current <see cref="HttpContext"/>.</param>
/// <returns></returns>
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;
}
/// <summary>
/// Clears a session when available.
/// </summary>
/// <param name="httpContext">The current <see cref="HttpContext"/>.</param>
public static void ClearSession(this HttpContext httpContext)
=> httpContext?.Session?.Clear();
}
}