0

I am sending HttpWebRequest(post ) to some api services.

Here is a code example : This is the post data params :

var postData = new Dictionary<string, string>
{
    {
        "OtherBankNames",
        dto.OtherBankNames
    },
    {
        "AccountOpeningMainReasonId",
        dto.AccountOpeningMainReasonId?.ToString()
    },
    {
        "ActivityCategoryId",
        dto.ActivityCategoryId?.ToString()
    },

    {
        "ActivitySubCategoryId",
        dto.ActivitySubCategoryId?.ToString()
    },

    {
        "AnnualTurnoverSalaryRateId",
        dto.AnnualTurnoverSalaryRateId?.ToString()
    },
...

dto is just a class ChatInfoDto.

Data passed correctly like this :

OtherBankNames=value&AccountOpeningMainReasonId=value... etc.

I have a helper method which converts postData Dictionary like query params :

public static string BuildPostTPayload(Dictionary<string, string> keyValuePairs)
{
    if (keyValuePairs.Count == 0)
        return null;

    var temp = keyValuePairs.Select(x => x.Key + "=" + System.Web.HttpUtility.UrlEncode(x.Value));
    var result = string.Join("&", temp);

    return result;
}

Everything works fine , I am just curious to know : is it possible to serialize object as a post params and not write each property manually like I do in Dictionary case?

So what I need is a magic method which serialize the whole T(generic class) like a query params

Nkosi
  • 235,767
  • 35
  • 427
  • 472
user3857731
  • 599
  • 1
  • 6
  • 18
  • Did you try using a `NameValueCollection`? https://stackoverflow.com/a/1877016/2707705 – Biscuits May 28 '17 at 16:08
  • Thanks for that link. WIth Dictionary I am doing almost the same. Class is huge and create that dictionary is tedious process – user3857731 May 28 '17 at 16:11
  • @user3857731 you can use reflection to inspect the object and create either the dictionary or the query string directly – Nkosi May 28 '17 at 17:25

0 Answers0