使用Microsoft.HttpClient和HttpContentExtensions的通用PO​​ST请求

时间:2011-01-20 16:46:52

标签: c# wcf rest httpclient

我正在使用WCF REST入门套件中提供的非常棒的HttpClient。我有以下方法来处理HelloTxt API:

public UserValidateResponse Validate()
{
    HttpClient client = new HttpClient(baseUrl);

    HttpMultipartMimeForm form = new HttpMultipartMimeForm();
    form.Add("app_key", this.AppKey);
    form.Add("user_key", this.UserKey);
    HttpResponseMessage response = client.Post("user.validate", form.CreateHttpContent());

    return response.Content.ReadAsXmlSerializable<UserValidateResponse>();
}

我有一个很好的通用GetRequest方法,如下所示:

public T GetRequest<T>(string query)
{
    HttpClient client = new HttpClient(baseUrl);
    client.DefaultHeaders.UserAgent.AddString(@"http://www.simply-watches.co.uk/");

    HttpResponseMessage response = client.Get(query);
    response.EnsureStatusIsSuccessful();

    T data = default(T);
    try
    {
        data = response.Content.ReadAsXmlSerializable<T>();
        return data;
    }
    catch (Exception ex)
    {
        Console.Write(String.Format("{0}: {1}", ex.Message, ex.InnerException.Message));
    }

    return data;
}

其好处是您可以将T作为响应类型传递,如下随机示例所示:

public List<User> GetUsers(int deptid)
{
    string query = String.Format("department.getUsers?api_key={0}&dept_id={1}", this.APIKey, deptId);

    return GetRequest<List<User>>(query);
}

我现在想要使用相同的通用样式POST方法,而不是GET,我确信我可以使用HttpContentExtensions,但我无法弄清楚如何将请求转换为HttpMultipartMimeForm。这就是我到目前为止所做的:

public T PostRequest<K, T>(string query, K request)
{
    HttpClient client = new HttpClient(baseUrl);
    // the following line doesn't work! Any suggestions?
    HttpContent content = HttpContentExtensions.CreateDataContract<K>(request, Encoding.UTF8, "application/x-www-form-urlencoded", typeof(HttpMultipartMimeForm));

    HttpResponseMessage response = client.Post(query, content);
    response.EnsureStatusIsSuccessful();

    T data = default(T);
    try
    {
        data = response.Content.ReadAsXmlSerializable<T>();
        return data;
    }
    catch (Exception ex)
    {
        Console.Write(String.Format("{0}: {1}", ex.Message, ex.InnerException.Message));
    }

    return data;
}

它将被称为:

UserValidateResponse response = PostRequest<UserValidateRequest, UserValidateResponse>("user.validate", new UserValidateRequest(this.AppKey, this.UserKey));

这是针对此API:http://hellotxt.com/developers/documentation。任何建议都非常欢迎!我可以为每个POST定义一个不同的表单,但一般来说这样做会很好。

1 个答案:

答案 0 :(得分:2)

我回答了我自己的问题。代码可以在我的.NET wrapper for the HelloTxt API - HelloTxt.NET中看到,根据我上面的评论,使用反射来计算请求对象属性,并使用值填充HttpMultipartMimeForm(),同时检查Required关于类属性的数据注释。

有问题的代码是:

/// <summary>
/// Generic post request.
/// </summary>
/// <typeparam name="K">Request Type</typeparam>
/// <typeparam name="T">Response Type</typeparam>
/// <param name="query">e.g. user.validate</param>
/// <param name="request">The Request</param>
/// <returns></returns>
public T PostRequest<K, T>(string query, K request)
{
    using (var client = GetDefaultClient())
    {
        // build form data post
        HttpMultipartMimeForm form = CreateMimeForm<K>(request);

        // call method
        using (HttpResponseMessage response = client.Post(query, form.CreateHttpContent()))
        {
            response.EnsureStatusIsSuccessful();
            return response.Content.ReadAsXmlSerializable<T>();
        }
    }
}

/// <summary>
/// Builds a HttpMultipartMimeForm from a request object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="request"></param>
/// <returns></returns>
public HttpMultipartMimeForm CreateMimeForm<T>(T request)
{
    HttpMultipartMimeForm form = new HttpMultipartMimeForm();

    Type type = request.GetType();
    PropertyInfo[] properties = type.GetProperties();
    foreach (PropertyInfo property in properties)
    {
        foreach (Attribute attribute in property.GetCustomAttributes(true))
        {
            RequiredAttribute requiredAttribute = attribute as RequiredAttribute;
            if (requiredAttribute != null)
            {
                if (!requiredAttribute.IsValid(property.GetValue(request, null)))
                {
                    //Console.WriteLine("{0} [type = {1}] [value = {2}]", property.Name, property.PropertyType, property.GetValue(property, null));
                    throw new ValidationException(String.Format("{0} [type = {1}] requires a valid value", property.Name, property.PropertyType));
                }
            }
        }

        if (property.PropertyType == typeof(FileInfo))
        {
            FileInfo fi = (FileInfo)property.GetValue(request, null);
            HttpFormFile file = new HttpFormFile();
            file.Content = HttpContent.Create(fi, "application/octet-stream");
            file.FileName = fi.Name;
            file.Name = "image";

            form.Files.Add(file);
        }
        else
        {
            form.Add(property.Name, String.Format("{0}", property.GetValue(request, null)));
        }
    }

    return form;
}