Search code examples
asp.net-coremiddleware

How to modify form & querystring values at middleware in asp.net core?


I have Created a middleware class. The purpose of this class is to make some changes in all form and querystring values but there is a problem! form and querystring values are readonly and I can not change them. how can do it?

public class TestMiddleware
{
    private readonly RequestDelegate _next;

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

    public async Task Invoke(HttpContext httpContext)
    {
        var collection = httpContext.Request.Query;

        foreach (var item in collection)
        {
            collection[item.Key] = item.Value.ToString().Replace('x', 'y');
        }

        httpContext.Request.Query = collection;

        var collection2 = httpContext.Request.Form;

        foreach (var item in collection2)
        {
            collection2[item.Key] = item.Value.ToString().Replace('x', 'y');
        }

        httpContext.Request.Form = collection2;

        await _next(httpContext);

    }
}

// Extension method used to add the middleware to the HTTP request pipeline.
public static class TestMiddlewareExtensions
{
    public static IApplicationBuilder UseTest(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<TestMiddleware>();
    }
}

Solution

  • You cannot modify the form & querystring values directly because they are read-only, you can only try to replace it.

    Try to change your middleware like below:

    public class TestMiddleware
    {
        private readonly RequestDelegate _next;
        
        public TestMiddleware(RequestDelegate next)
        {
            _next = next;
            
        }
    
        public async Task Invoke(HttpContext httpContext)
        {
            var queryitems = httpContext.Request.Query.SelectMany(x => x.Value, (col, value) => new KeyValuePair<string, string>(col.Key, value)).ToList();
            List<KeyValuePair<string, string>> queryparameters = new List<KeyValuePair<string, string>>();
            foreach(var item in queryitems)
            {
                var value = item.Value.ToString().Replace("x", "y");
                KeyValuePair<string, string> newqueryparameter = new KeyValuePair<string, string>(item.Key, value);
                queryparameters.Add(newqueryparameter);                
            }
            
             var contentType = httpContext.Request.ContentType;
    
            if (contentType != null && contentType.Contains("multipart/form-data"))
            {
                var formitems = httpContext.Request.Form.SelectMany(x => x.Value, (col, value) => new KeyValuePair<string, string>(col.Key, value)).ToList();
    
                Dictionary<string, StringValues> formparameters = new Dictionary<string, StringValues>();
                foreach (var item in formitems)
                {
                    var value = item.Value.ToString().Replace("x", "y");
                    formparameters.Add(item.Key, value);
                };
    
                var qb1 = new QueryBuilder(queryparameters);
                var qb2 = new FormCollection(formparameters);
                httpContext.Request.QueryString = qb1.ToQueryString();
                httpContext.Request.Form = qb2;
    
                var items2 = httpContext.Request.Query.SelectMany(x => x.Value, (col, value) => new KeyValuePair<string, string>(col.Key, value)).ToList();
                var items3 = httpContext.Request.Form.SelectMany(x => x.Value, (col, value) => new KeyValuePair<string, string>(col.Key, value)).ToList();
            }        
    
            await _next(httpContext);
    
        }
    }
    
    public static class TestMiddlewareExtensions
    {
        public static IApplicationBuilder UseTest(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<TestMiddleware>();
        }
    }
    

    Results: enter image description here