7

I have an HttpContext.Request object that has data in the Form that is wrong and I want to fix it up and send the correct HttpContext on its way. HttpContext.Request.Form is readonly, but if it wasn't I would have simply done the following; HttpContext.Request.Form["a"] = "the correct value for a";

So, where is the best place in the pipeline to do this. Is it possible to make the HttpContext.Request.Form write accessable via reflection?

2
  • What exactly do you mean by "send the correct HttpContext on its way?" Are you passing it to another method/object or are you trying to send it back to the client?
    – greenjaed
    Commented Mar 9, 2017 at 23:49
  • I am interceping incoming requests and fixing up bad form data in middleware, and sending good form data down the rest of the incomming pipeline.
    – Herb Stahl
    Commented Mar 10, 2017 at 16:43

5 Answers 5

10

This was easier than I thought. I am doing this in my middleware which is there to correct bad form data that came in.

public async Task Invoke(HttpContext context)
{
    ....
    NameValueCollection fcnvc = context.Request.Form.AsNameValueCollection();
    fcnvc.Set("a", "the correct value of a");
    fcnvc.Set("b", "a value the client forgot to post");
    Dictionary<string, StringValues> dictValues = new Dictionary<string, StringValues>();
    foreach (var key in fcnvc.AllKeys)
    {
      dictValues.Add(key, fcnvc.Get(key));
    }
    var fc = new FormCollection(dictValues);
    context.Request.Form = fc;
    ....
    await _next.Invoke(context);
}

Interestingly the FormCollection is readonly, but the HttpContext.Request object is not thus allowing me to replace the entire Form.

2
  • I don't have AsNameValueCollection extension method! where is it? Commented Dec 28, 2017 at 4:18
  • AsNameValueCollection is inside of IdentityServer4.dll, I posted the source code below.
    – Herb Stahl
    Commented Jan 27, 2018 at 3:51
3

Here's a .NET Core/5 solution that worked for me without using the Identity Server package.

Basically you build a new dictionary of type <string, StringValues> out of the existing form collection, modify the values in the dictionary how you want, then create a new FormCollection from that dictionary and set it to context.Request.Form. The important thing to remember is that the value which is of type StringValues is just an array of strings!

This example demonstrates me removing a "client_id" field from the request form.

var formDictionary = new Dictionary<string, StringValues>();
var form = context.Request.Form;

foreach (var key in form.Keys)
{
    // Only add if key is NOT client_id
    if (key != "client_id")
    {
        form.TryGetValue(key, out StringValues formValues);

        formDictionary.Add(key, formValues);
    }
}

FormCollection formCollection = new FormCollection(formDictionary);

context.Request.Form = formCollection;

Here is another example of me changing the "client_id" field to "NewValue"

var formDictionary = new Dictionary<string, StringValues>();
var form = context.Request.Form;

foreach (var key in form.Keys)
{
    form.TryGetValue(key, out StringValues formValues);

    // Change client_id value to "NewValue"
    if (key == "client_id")
    {
        formValues = new string[] { "NewValue" };
    }

    formDictionary.Add(key, formValues);
}

FormCollection formCollection = new FormCollection(formDictionary);

context.Request.Form = formCollection;
1

AsNameValueCollection is inside of IdentityServer4.dll.

public static class IReadableStringCollectionExtensions
{
    [DebuggerStepThrough]
    public static NameValueCollection AsNameValueCollection(this IDictionary<string, StringValues> collection)
    {
        NameValueCollection values = new NameValueCollection();
        foreach (KeyValuePair<string, StringValues> pair in collection)
        {
            string introduced3 = pair.get_Key();
            values.Add(introduced3, Enumerable.First<string>(pair.get_Value()));
        }
        return values;
    }

    [DebuggerStepThrough]
    public static NameValueCollection AsNameValueCollection(this IEnumerable<KeyValuePair<string, StringValues>> collection)
    {
        NameValueCollection values = new NameValueCollection();
        foreach (KeyValuePair<string, StringValues> pair in collection)
        {
            string introduced3 = pair.get_Key();
            values.Add(introduced3, Enumerable.First<string>(pair.get_Value()));
        }
        return values;
    }
}
1

I personally prefer to use an extended method to do this.

public static IFormCollection PushToForm(this IFormCollection form, Dictionary<string, StringValues> data)
{
    var formDictionary = new Dictionary<string, StringValues>();
    foreach (var k in form.Keys)
    {
        form.TryGetValue(k, out StringValues v);
        formDictionary.Add(k, v);
    }

    foreach (var x in data) formDictionary.Add(x.Key, x.Value);
    return new FormCollection(formDictionary);
}

Example:

Request.Form = Request.Form.PushToForm(new Dictionary<string, StringValues>()
{
    { "key1", new string[] { "value1" } },
    { "key2", new string[] { "value2" } },
    { "key3", new string[] { "value3" } },
    ...
});
0

A bit complex but shorter solution

var collection = HttpContext.Request.Form;
var propInfo = collection.GetType().GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
propInfo.SetValue(collection, false, new object[]{});
collection.Remove("a");
collection.Add("a", "the correct value for a");

System.Diagnostics.Debug.Write(HttpContext.Request["a"]); // the correct value for a

Enjoy!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.