如何从WinRT调用Web API

时间:2015-03-15 17:18:07

标签: c# asp.net-web-api windows-runtime

我尝试从WinRT调用WebAPI。在WinRT中,我编写了可序列化的类,我希望将其发送到WebAPI:

[DataContractAttribute]
public class RecognizeItem
{
    [DataMember()]
    public string Id { get; set; }

    [DataMember()]
    public Windows.UI.Xaml.Media.Imaging.BitmapImage Image { get; set; }
}

下一步将数据发送到服务器:

            RecognizeItem system = new RecognizeItem()
            {
                Id = login,
                Image = LoadImage
            };
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            string json = JsonConvert.SerializeObject(system);
            HttpContent content = new StringContent(json); 
            HttpResponseMessage response = await client.PostAsync("api/RecognizeItem/", content);

在webAPI的实现中,我实现了一个可序列化的类,如下所示:

[Serializable]
public class RecognizeItem
{
    public string Id { get; set; }

    public Bitmap Image { get; set; }

}

我的ApiController:

public string Post([FromBody] RecognizeItem image)...

但作为回应,我看到以下状态:

  

StatusCode:415,ReasonPhrase:'不支持的媒体类型'

如何解决此错误?

1 个答案:

答案 0 :(得分:0)

我认为Content-Type是内容的标题,而不是请求的标题。

尝试通过将content-type传递给StringContent构造函数来设置内容:

替换

HttpContent content = new StringContent(json);

通过

HttpContent content = new StringContent(json,
                                Encoding.UTF8, 
                                "application/json");