FormUrlEncodedContent与LIST对象和POST方法的其他混合数据类型

时间:2018-05-02 22:59:46

标签: c# .net web-services asp.net-web-api http-post

POST方法

SaveData([FromBody]MyDetails myDetails)

MyDetails是一个带

的课程
public int Id;
public int LocationId;
public List<Employee> Employee;
public bool Status;

员工是

的班级
public int EmployeeId;
public Name EmployeeName;



var values = new Dictionary<string, string>
                        {
                            {"Id",myDetails.Id.ToString()},
                            {"LocationId", myDetails.LocationId.ToString()},
                            {"Status", myDetails.Status.ToString()},
                 {"Employee", myDetails.Employee.ToString()} -- How do i send List Employee part of FormURLEncodedContent, i know this is wrong, i am having hard time getting this to work?

                        };

var encodedContent = new FormUrlEncodedContent(values);
 var response = await client.PostAsync(url, encodedContent); //url points to POST method SaveData, which accepts MyDetails class object as parameter.

2 个答案:

答案 0 :(得分:0)

序列化类objecto JSON

var content = JsonConvert.SerializeObject(myDetails); //myDetails is my class object.
var buffer = System.Text.Encoding.UTF8.GetBytes(content);
var byteContent = new ByteArrayContent(buffer);
byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");   

 var response = await client.PostAsync(url, byteContent);

产生了正确的结果。

答案 1 :(得分:0)

我已经做到了。 这是我的课程详细信息

 public class AddTenantRequestdto
{
    public IFormFile TenantLogo { get; set; }    
    public string TenantTitle { get; set; } 
    public List<string> ApplicationName { get; set; }  
    public bool EnableOTP { get; set; }

}

这是我的API

    public async Task Tenant_Create_Success(AddTenantRequestdto addTenantRequest)
            {
                HttpClient Client = new HttpClient();

               var tenantData = addTenantRequestdto.ToFormData();          

    var response = await _TestFixture.Client.PostAsync("http://localhost:61234/Tenants/CreateTenant", tenantData);

                response.StatusCode.Should().Be(HttpStatusCode.OK);
            }

扩展方法在这里,添加Newtonsoft.Json包:-

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

        // Added by me: avoid cyclic references
        var serializer = new JsonSerializer { ReferenceLoopHandling = ReferenceLoopHandling.Ignore };
        var token = metaToken as JToken;
        if (token == null)
        {
            // Modified by me: use serializer defined above
            return ToKeyValue(JObject.FromObject(metaToken, serializer));
        }

        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 } };
    }

    public static FormUrlEncodedContent ToFormData(this object obj)
    {
        var formData = obj.ToKeyValue();

        return new FormUrlEncodedContent(formData);
    }
}

希望我的解释很好,对我来说也很好