123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307 |
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Threading;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc.Controllers;
- using Microsoft.Extensions.Primitives;
- namespace TEAMModelOS.SDK.Extension
- {
- public static class HttpContextExtensions
- {
- /// <summary>
- /// 取得驗證金鑰,Authorization
- /// </summary>
- public static string GetToken(this HttpContext httpContext)
- {
- return httpContext.Request.Headers["Authorization"].ToString();
- }
- /// <summary>
- /// 获取 Action 特性
- /// </summary>
- /// <typeparam name="TAttribute"></typeparam>
- /// <param name="httpContext"></param>
- /// <returns></returns>
- public static TAttribute GetMetadata<TAttribute>(this HttpContext httpContext)
- where TAttribute : class
- {
- return httpContext.GetEndpoint()?.Metadata?.GetMetadata<TAttribute>();
- }
- /// <summary>
- /// 获取 控制器/Action 描述器
- /// </summary>
- /// <param name="httpContext"></param>
- /// <returns></returns>
- public static ControllerActionDescriptor GetControllerActionDescriptor(this HttpContext httpContext)
- {
- return httpContext.GetEndpoint()?.Metadata?.FirstOrDefault(u => u is ControllerActionDescriptor) as ControllerActionDescriptor;
- }
- /// <summary>
- /// 获取本机 IPv4地址
- /// </summary>
- /// <param name="context"></param>
- /// <returns></returns>
- public static string GetLocalIpAddressToIPv4(this HttpContext context)
- {
- return context.Connection.LocalIpAddress?.MapToIPv4()?.ToString();
- }
- /// <summary>
- /// 获取本机 IPv6地址
- /// </summary>
- /// <param name="context"></param>
- /// <returns></returns>
- public static string GetLocalIpAddressToIPv6(this HttpContext context)
- {
- return context.Connection.LocalIpAddress?.MapToIPv6()?.ToString();
- }
- /// <summary>
- /// 获取远程 IPv4地址
- /// </summary>
- /// <param name="context"></param>
- /// <returns></returns>
- public static string GetRemoteIpAddressToIPv4(this HttpContext context)
- {
- return context.Connection.RemoteIpAddress?.MapToIPv4()?.ToString();
- }
- /// <summary>
- /// 获取远程 IPv6地址
- /// </summary>
- /// <param name="context"></param>
- /// <returns></returns>
- public static string GetRemoteIpAddressToIPv6(this HttpContext context)
- {
- return context.Connection.RemoteIpAddress?.MapToIPv6()?.ToString();
- }
- /// <summary>
- /// 获取完整请求地址
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public static string GetRequestUrlAddress(this HttpRequest request)
- {
- return new StringBuilder()
- .Append(request.Scheme)
- .Append("://")
- .Append(request.Host)
- .Append(request.PathBase)
- .Append(request.Path)
- .Append(request.QueryString)
- .ToString();
- }
- /// <summary>
- /// 获取来源地址
- /// </summary>
- /// <param name="request"></param>
- /// <param name="refererHeaderKey"></param>
- /// <returns></returns>
- public static string GetRefererUrlAddress(this HttpRequest request, string refererHeaderKey = "Referer")
- {
- return request.Headers[refererHeaderKey].ToString();
- }
- /// <summary>
- /// 读取 Body 内容
- /// </summary>
- /// <param name="httpContext"></param>
- /// <remarks>需先在 Startup 的 Configure 中注册 app.EnableBuffering()</remarks>
- /// <returns></returns>
- public static async Task<string> ReadBodyContentAsync(this HttpContext httpContext)
- {
- if (httpContext == null) return default;
- return await httpContext.Request.ReadBodyContentAsync();
- }
- /// <summary>
- /// 读取 Body 内容
- /// </summary>
- /// <param name="request"></param>
- /// <remarks>需先在 Startup 的 Configure 中注册 app.EnableBuffering()</remarks>
- /// <returns></returns>
- public static async Task<string> ReadBodyContentAsync(this HttpRequest request)
- {
- request.Body.Seek(0, SeekOrigin.Begin);
- using var reader = new StreamReader(request.Body, Encoding.UTF8, true, 1024, true);
- var body = await reader.ReadToEndAsync();
- // 回到顶部,解决此类问题 https://gitee.com/dotnetchina/Furion/issues/I6NX9E
- request.Body.Seek(0, SeekOrigin.Begin);
- return body;
- }
-
- /// <summary>
- /// 判断是否是 WebSocket 请求
- /// </summary>
- /// <param name="context"></param>
- /// <returns></returns>
- public static bool IsWebSocketRequest(this HttpContext context)
- {
- return context.WebSockets.IsWebSocketRequest || context.Request.Path == "/ws";
- }
- /// <summary>
- /// 设置响应头 Tokens
- /// </summary>
- /// <param name="httpContext"></param>
- /// <param name="accessToken"></param>
- /// <param name="refreshToken"></param>
- public static void SetTokensOfResponseHeaders(this HttpContext httpContext, string accessToken, string refreshToken = null)
- {
- httpContext.Response.Headers["access-token"] = accessToken;
- if (!string.IsNullOrWhiteSpace(refreshToken))
- {
- httpContext.Response.Headers["x-access-token"] = refreshToken;
- }
- }
- /// <summary>
- /// 取得JWT驗證金鑰,Authorization Bearer
- /// </summary>
- /// <param name="httpContext"></param>
- /// <returns></returns>
- public static string GetJwtToken(this HttpContext httpContext)
- {
- var token = string.Empty;
- string authorization = httpContext.Request.Headers["Authorization"].ToString();
- if (!string.IsNullOrWhiteSpace(authorization) && authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
- {
- token = authorization.Substring("Bearer ".Length).Trim();
- }
- return token;
- }
- /// <summary>
- /// 取得遠端呼叫的IP
- /// </summary>
- public static string GetRemoteIP(this HttpContext httpContext)
- {
- return httpContext?.Connection?.RemoteIpAddress?.ToString();
- }
- /// <summary>
- /// 取得X-Auth-Key值
- /// </summary>
- /// <param name="key">Key Name</param>
- /// <returns></returns>
- public static string GetXAuth(this HttpContext httpContext, string key = null)
- {
- try
- {
- if (httpContext.Request.Headers.TryGetValue($"X-Auth-{key}", out StringValues value))
- return value.ToString();
- else
- return null;
- }
- catch
- {
- return null;
- }
- }
- /// <summary>
- /// 取得AuthToken權杖資訊
- /// </summary>
- /// <param name="key">Key Name</param>
- /// <returns></returns>
- public static (string id, string school) GetApiTokenInfo(this HttpContext httpContext, string key = null)
- {
- object id = null, school = null;
- httpContext?.Items.TryGetValue("ID", out id);
- httpContext?.Items.TryGetValue("School", out school);
- return (id?.ToString(), school?.ToString());
- }
- /// <summary>
- /// 取得AuthToken權杖資訊
- /// </summary>
- /// <param name="key">Key Name</param>
- /// <returns></returns>
- public static (string id, string name, string picture, string school) GetAuthTokenInfo(this HttpContext httpContext, string key = null)
- {
- object id = null, name = null, picture = null, school = null;
- httpContext?.Items.TryGetValue("ID", out id);
- httpContext?.Items.TryGetValue("Name", out name);
- httpContext?.Items.TryGetValue("Picture", out picture);
- httpContext?.Items.TryGetValue("School", out school);
- return (id?.ToString(), name?.ToString(), picture?.ToString(), school?.ToString());
- }
- /// <summary>
- /// 取得AuthToken權杖資訊
- /// </summary>
- /// <param name="key">Key Name</param>
- /// <returns></returns>
- public static (string id, string name, string picture, string school, string area, string keyData) GetAuthTokenKey(this HttpContext httpContext, string key = null)
- {
- object id = null, name = null, picture = null, school = null, area = null, keyData = null;
- httpContext?.Items.TryGetValue("ID", out id);
- httpContext?.Items.TryGetValue("Name", out name);
- httpContext?.Items.TryGetValue("Picture", out picture);
- httpContext?.Items.TryGetValue("School", out school);
- httpContext?.Items.TryGetValue("Area", out area);
- if (!string.IsNullOrWhiteSpace(key))
- {
- httpContext?.Items.TryGetValue(key, out keyData);
- }
- return (id?.ToString(), name?.ToString(), picture?.ToString(), school?.ToString(), area?.ToString(), keyData?.ToString());
- }
- /// <summary>
- /// 取得User-Agent值
- /// </summary>
- public static string GetUserAgent(this HttpContext httpContext)
- {
- try
- {
- return httpContext.Request.Headers["User-Agent"].ToString();
- }
- catch
- {
- return null;
- }
- }
- /// <summary>
- /// 取得Scheme值
- /// </summary>
- public static string GetScheme(this HttpContext httpContext)
- {
- return httpContext?.Request?.Scheme;
- }
- /// <summary>
- /// 取得HostName值
- /// </summary>
- public static string GetHostName(this HttpContext httpContext)
- {
- return httpContext?.Request?.Host.ToString();
- }
- /// <summary>
- /// 设置本地cookie
- /// </summary>
- /// <param name="key">键</param>
- /// <param name="value">值</param>
- /// <param name="minutes">过期时长,单位:分钟</param>
- public static void SetCookies(HttpResponse Response, string key, string value, int minutes = 30)
- {
- Response.Cookies.Append(key, value, new CookieOptions
- {
- Expires = DateTimeOffset.Now.AddMinutes(minutes)
- });
- }
- /// <summary>
- /// 删除指定的cookie
- /// </summary>
- /// <param name="key">键</param>
- public static void DeleteCookies(HttpContext httpContext, string key)
- {
- httpContext.Response.Cookies.Delete(key);
- }
- }
- }
|