ChouBox/Utile/HuanMeng.DotNetCore/Extensions/HttpContextExtensions.cs
2025-04-23 19:20:23 +08:00

48 lines
1.5 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Microsoft.AspNetCore.Http;
using System.Text;
using System.Web;
namespace HuanMeng.DotNetCore.Extensions
{
/// <summary>
/// HttpContext扩展方法
/// </summary>
public static class HttpContextExtensions
{
/// <summary>
/// 动态消息的头部名称
/// </summary>
public const string DynamicMessageHeaderName = "X-Dynamic-Message";
/// <summary>
/// 设置动态消息
/// </summary>
/// <param name="httpContext">HTTP上下文</param>
/// <param name="message">消息内容</param>
public static void SetDynamicMessage(this HttpContext httpContext, string message)
{
if (string.IsNullOrEmpty(message))
return;
// URL编码消息内容防止特殊字符导致问题
string encodedMessage = HttpUtility.UrlEncode(message);
httpContext.Response.Headers[DynamicMessageHeaderName] = encodedMessage;
}
/// <summary>
/// 获取动态消息
/// </summary>
/// <param name="httpContext">HTTP上下文</param>
/// <returns>消息内容,如果不存在则返回空字符串</returns>
public static string GetDynamicMessage(this HttpContext httpContext)
{
if (httpContext.Response.Headers.TryGetValue(DynamicMessageHeaderName, out var value))
{
// URL解码消息内容
return HttpUtility.UrlDecode(value);
}
return string.Empty;
}
}
}