-2

I have below api url

http://myapi/api/getproduct?

These parameters will get created from below class

public class ApiParamters
{
   public string id {get;set;}
   public string name {get;set;}
   public List<string> otherNames {get;set;}
}

If value of above parameters are

id=1
name="product1"
OtherNames="oldProduct1" and "oldProduct2"

Then api url should be as below

http://myapi/api/getproduct?id=1&name=product1&OtherNames=oldProduct1&OtherNames=oldProduct2

How to dynamically create these kind of url (GENERIC SOLUTION IS REQUREID because I have to implement simliar logic for other APIs too)

Gaurav123
  • 5,059
  • 6
  • 51
  • 81
  • [Build query string for System.Net.HttpClient get](//stackoverflow.com/a/17096289) – 001 May 16 '20 at 00:18
  • I used foreach in c#, it worked for me but i don't know how to make generic solution for this – Gaurav123 May 16 '20 at 00:20
  • My solution is big so I didn't mention here – Gaurav123 May 16 '20 at 00:21
  • You could use reflection: [GetFields()](https://learn.microsoft.com/en-us/dotnet/api/system.type.getfields?redirectedfrom=MSDN&view=netcore-3.1#System_Type_GetFields). Can you be more specific about where you are having issues? – 001 May 16 '20 at 00:22
  • @Gaurav123 try something like this : https://stackoverflow.com/questions/60338449/serialise-an-object-to-url-parameter-string-including-properties-from-nested-o/60357537#60357537 – Mohammed Sajid May 16 '20 at 00:26

1 Answers1

0

Here's what I came up with using reflection. I'm sure it doesn't handle all the cases, but see if it works for you.

using System.Web;
using System.Reflection;
using System.Collections.Generic;

class Program {
    public static string toQueryString(string url, object o)
    {
        var query = HttpUtility.ParseQueryString(string.Empty);

        FieldInfo[] myField = o.GetType().GetFields();

        for (int i = 0; i < myField.Length; i++)
        {
            // Is it a list?
            var t = myField[i].GetValue(o) as System.Collections.IEnumerable;
            if (t != null)
            {
                dynamic lst = myField[i].GetValue(o);
                int index = 1;
                foreach (dynamic oo in lst)
                {
                    query[myField[i].Name + index++] = oo.ToString();
                }
            }
            else
            {
                query[myField[i].Name] = myField[i].GetValue(o).ToString();
            }
        }
        return query.Count == 0 ? url : url + "?" + query.ToString();
    }
}
001
  • 13,291
  • 5
  • 35
  • 66