Search code examples
c#.net-coreasp.net-core-8

Convert IFormCollection to NameValueCollection


I am trying to port .net3.1 code to .net8 class library where I have below code

private static void ReadForm(Dictionary<string, GatewayParameter> gatewayParameterList)
{
    NameValueCollection form = HttpContext.Request.Form;
    foreach (string item in form.AllKeys)
    {
        SetGatewayParameterValue(gatewayParameterList, item, form[item], HttpMethod.Post);
    }
}

But I am getting below error;

Error CS0266 Cannot implicitly convert type 'Microsoft.AspNetCore.Http.IFormCollection' to 'System.Collections.Specialized.NameValueCollection'. An explicit conversion exists (are you missing a cast?)

I know that HttpContext.Request.Form returns NameValueCollection but then why this error?


Solution

  • ASP.NET Core's HttpRequest.Form doesn't return a NameValueCollection, it returns an IFormCollection since .NET Core 1.0. You probably confused this with .NET Framework's HttpRequest.Form property.

    IFormCollection implements IEnumerable<KeyValuePair<>> which means you can iterate over it instead of trying to access items through AllKeys :

    var form = HttpContext.Request.Form;
    foreach (var (key,value) in form)
    {
        SetGatewayParameterValue(gatewayParameterList, key, value, HttpMethod.Post);
    }