c#从HttpClient的模型对象构建URL编码查询 [英] c# Build URL encoded query from model object for HttpClient

查看:155
本文介绍了c#从HttpClient的模型对象构建URL编码查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要从HttpClient的模型对象构建URL编码查询

Need to build URL encoded query from model object for HttpClient

我的模型是

class SaveProfileRequest
{
    public string gName { get; set; }
    public string gEmail { get; set; }
    public long gContact { get; set; }
    public string gCompany { get; set; }
    public string gDeviceID { get; set; }
    public string Organization { get; set; }
    public string profileImage { get; set; }
    public string documentImagefront { get; set; }
    public string documentImageback { get; set; }
}

SaveProfileRequest request = new SaveProfileRequest() { gName = name, gEmail = email, gContact = phonenumber, gCompany = company,
            gDeviceID = deviceId, Organization = "", profileImage = "", documentImageback = "", documentImagefront = "" };

string response = await RequestProvider.PostAsync<string, SaveProfileRequest>(uri, request);

我有针对内容类型JSON的工作代码

I have a working code for content type JSON

content = new StringContent(JsonConvert.SerializeObject(data));

content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

数据类型为TInput的情况

Where data is of type TInput

尝试过

content = new StringContent(System.Net.WebUtility.UrlEncode(JsonConvert.SerializeObject(data)));

content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");

但没有锻炼

推荐答案

JsonConvert 仅生成json内容。对于urlencoded查询,您应该构造 FormUrlEncodedContent 的实例。作为构造函数参数,它需要收集 KeyValuePair< string,string> 。因此,主要技巧是为模型对象构建此集合。

JsonConvert produces only json content. For urlencoded query you should construct instance of FormUrlEncodedContent. As constructor parameter it takes collection of KeyValuePair<string, string>. So the main trick is to build this collection for model object.

您可以为此使用反射。但是有一个基于Json.net的更简单的解决方案。在此处及其后进行了描述 ToKeyValue()扩展方法是该博客文章的副本/粘贴:

You could use reflection for this purpose. But there is a simpler solution based on Json.net. It was described here and following ToKeyValue() extension method is a copy/paste from that blog post:

public static class ObjectExtensions
{
    public static IDictionary<string, string> ToKeyValue(this object metaToken)
    {
        if (metaToken == null)
        {
            return null;
        }

        JToken token = metaToken as JToken;
        if (token == null)
        {
            return ToKeyValue(JObject.FromObject(metaToken));
        }

        if (token.HasValues)
        {
            var contentData = new Dictionary<string, string>();
            foreach (var child in token.Children().ToList())
            {
                var childContent = child.ToKeyValue();
                if (childContent != null)
                {
                    contentData = contentData.Concat(childContent)
                        .ToDictionary(k => k.Key, v => v.Value);
                }
            }

            return contentData;
        }

        var jValue = token as JValue;
        if (jValue?.Value == null)
        {
            return null;
        }

        var value = jValue?.Type == JTokenType.Date ?
            jValue?.ToString("o", CultureInfo.InvariantCulture) :
            jValue?.ToString(CultureInfo.InvariantCulture);

        return new Dictionary<string, string> { { token.Path, value } };
    }
}

现在,您可以轻松构建url编码的内容

Now you could build the url-encoded content as easy as:

var keyValues = data.ToKeyValue();
var content = new FormUrlEncodedContent(keyValues);

这篇关于c#从HttpClient的模型对象构建URL编码查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆