Refactoring
This commit is contained in:
63
AMWD.Common.AspNetCore/Extensions/HttpContextExtensions.cs
Normal file
63
AMWD.Common.AspNetCore/Extensions/HttpContextExtensions.cs
Normal file
@@ -0,0 +1,63 @@
|
||||
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 web context.</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 web context.</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>
|
||||
/// Tries to retrieve the return url.
|
||||
/// </summary>
|
||||
/// <param name="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();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user