123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116 |
- using System;
- using System.Collections.Generic;
- using System.Text;
- using Microsoft.AspNetCore.Http;
- 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>
- /// 取得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>
- /// 取得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 = DateTime.Now.AddMinutes(minutes)
- });
- }
- /// <summary>
- /// 删除指定的cookie
- /// </summary>
- /// <param name="key">键</param>
- public static void DeleteCookies(HttpContext httpContext, string key)
- {
- httpContext.Response.Cookies.Delete(key);
- }
- }
- }
|