using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using System;
using System.Text.RegularExpressions;
namespace Core.Util
{
/// <summary>
///Expand the class
/// </summary>
public static partial class Extention
{
/// <summary>
///Determine whether it is an AJAX request
/// </summary>
/// <param name="req"></param>
/// <returns></returns>
public static bool IsAjaxRequest(this HttpRequest req)
{
bool result = false;
var xreq = req.Headers.ContainsKey("x-requested-with");
if (xreq)
{
result = req.Headers["x-requested-with"] = ="XMLHttpRequest";
}
return result;
}
/// <summary>
///Gets the Url to remove query parameters
/// </summary>
/// <param name="req">request</param>
/// <returns></returns>
public static string GetDisplayUrlNoQuery(this HttpRequest req)
{
var queryStr = req.QueryString.ToString();
var displayUrl = req.GetDisplayUrl();
return queryStr.IsNullOrEmpty() ? displayUrl : displayUrl.Replace(queryStr, "");
}
/// <summary>
///Access Token
/// </summary>
/// <param name="req">request</param>
/// <returns></returns>
public static string GetToken(this HttpRequest req)
{
string tokenHeader = req.Headers["Authorization"].ToString();
if (tokenHeader.IsNullOrEmpty())
return null;
string pattern = "^Bearer (.*?) $";
if(! Regex.IsMatch(tokenHeader, pattern))throw new Exception("Wrong token format! Format :Bearer {token}");
string token = Regex.Match(tokenHeader, pattern).Groups[1]? .ToString();if (token.IsNullOrEmpty())
throw new Exception("Token cannot be empty!");
return token;
}
/// <summary>
///Payload of the Token is obtained
/// </summary>
/// <param name="req">request</param>
/// <returns></returns>
public static JWTPayload GetJWTPayload(this HttpRequest req)
{
string token = req.GetToken();
var payload = JWTHelper.GetPayload<JWTPayload>(token);
returnpayload; }}}Copy the code