在Web API中使用FormUrlEncoded OR Json发布数据

时间:2019-05-15 10:50:12

标签: c# asp.net-web-api asp.net-core asp.net-core-webapi

我创建了将数据发布到Web api的通用方法。在发布时,我将数据序列化为json。下面是我的通用方法。

public HttpResponseMessage GetData<T>(T parm, string url) where T : class
        {
            try
            {
                var client = new HttpClient();

                var result = client.PostAsync(url, SerializeData<T>(parm));

                result.Wait();

                if (result.Result.IsSuccessStatusCode)
                {
                    // Do something
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }

            return default(HttpResponseMessage);
        }

 private StringContent SerializeData<T>(T obj)
        {
            string mediaType = "application/json";

            string content = JsonConvert.SerializeObject(obj, formatter);

            return new StringContent(content, Encoding.UTF8, mediaType);
        }

如果我从调用方方法Like()传递类对象,则此方法正常工作

var result = service.GetData<MyClass>(myclassobj,url);

但是,对于某些通过传递类对象的URL无效。因此,我们编写了另一种方法,如下所示以 FormUrlEncodedContent 格式发布数据,并且效果很好。

var Parameters = new Dictionary<string, string> { { "Key1", "some value" }, { "Key2", "another value" } };
var EncodedContent = new FormUrlEncodedContent(Parameters);
var postTask = _client.PostAsync(url, EncodedContent);

我尝试将FormUrlEncoded数据发送到JSON方法并通过更改Media Type也进行了尝试。但是无法正确序列化它。我们正在使用的api /服务来自第三方提供商。

所以我的问题是,该方法需要进行哪些更改才能与所有格式(例如JSON,FormUrlEncodedContent等)一起使用。

此外,这是否取决于api的写入方式,它们仅适用于JSON,FormUrlEncodedContent等特定格式。

基本上,我正在尝试保留一种将支持所有格式的通用方法。

对此有任何帮助!

0 个答案:

没有答案