WEBAPI HTTP请求中所有的参数去除空格

WEBAPI HTTP请求中所有的参数去除空格

反正总会有一些沙雕需求。

总体思路就是要么中间件要么aop,拦截请求,对请求的参数做处理。
不知道大佬们有没有什么其他的思路来做,或者有更优的代码。

效果

img

调用方式

// 添加中间件,去掉请求中的空格
app.UseTrimRequest();

实现代码

using System.Text;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
public class TrimWhitespaceMiddleware
{
    private readonly RequestDelegate _next;

    public TrimWhitespaceMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        if (HttpMethods.IsGet(context.Request.Method) || HttpMethods.IsHead(context.Request.Method))
        {
            var originalQuery = context.Request.Query;
            var newQuery = originalQuery.ToDictionary(
                x => x.Key,
                x => x.Value.ToString().Trim()
            );
            context.Request.QueryString = QueryString.Create(newQuery);
        }
        else if (HttpMethods.IsPost(context.Request.Method) ||
                 HttpMethods.IsPut(context.Request.Method) ||
                 HttpMethods.IsDelete(context.Request.Method) ||
                 HttpMethods.IsPatch(context.Request.Method))
        {
            if (context.Request.HasFormContentType)
            {
                var form = await context.Request.ReadFormAsync();
                context.Request.Form = new FormCollection(form
                    .ToDictionary(x => x.Key, x => new StringValues(x.Value.ToString().Trim())));
            }
            else
            {
                using var reader = new StreamReader(context.Request.Body, Encoding.UTF8, false, 1024, true);
                string bodyAsString = await reader.ReadToEndAsync();
                var bodyAsJson = JObject.Parse(bodyAsString);
                await RemoveSpacesFromBodyAsync(bodyAsJson);
                string newBody = JsonConvert.SerializeObject(bodyAsJson, Formatting.None);
                byte[] newBodyBytes = Encoding.UTF8.GetBytes(newBody);

                context.Request.Body = new MemoryStream(newBodyBytes);
                context.Request.ContentLength = newBodyBytes.LongLength;
                context.Request.ContentType = "application/json";
            }
        }

        await _next.Invoke(context);
    }

    private static async Task RemoveSpacesFromBodyAsync(JObject body)
    {
        foreach (var property in body.Properties())
        {
            switch (property.Value)
            {
                case JValue { Type: JTokenType.String } jValue:
                    property.Value = jValue.Value?.ToString()?.Trim();
                    break;
                case JObject { } jObject:
                    await RemoveSpacesFromBodyAsync(jObject);
                    break;
                case JArray { } jArray:
                    await foreach (var item in GetObjectsInJArray(jArray))
                    {
                        await RemoveSpacesFromBodyAsync(item);
                    }
                    break;
            }
        }
    }

    private static async IAsyncEnumerable<JObject> GetObjectsInJArray(JArray jArray)
    {
        foreach (var item in jArray)
        {
            if (item is JObject obj)
            {
                yield return obj;
            }
        }
    }
}

public static class TrimRequestMiddlewareExtensions
{
    public static IApplicationBuilder UseTrimRequest(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<TrimWhitespaceMiddleware>();
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值