错误500向API发送JSON POST请求

时间:2017-05-25 16:45:14

标签: c# json rest xamarin.forms

我在Xamarin.Forms(共享项目库)中开发一个应用程序,它将自定义类型列表(只是文档编号和文件类型枚举)发送到本地托管的API。

如果我捕获JSON字符串并从Postman发送它,一切正常,但是一旦我从应用程序运行httpClient.PostAsync,我收到以下错误:

  

{StatusCode:500,ReasonPhrase:'内部服务器错误',版本:1.1,   内容:System.Net.Http.StreamContent,Headers:{Cache-Control:   no-cache Pragma:no-cache服务器:Microsoft-IIS / 7.5 X-AspNet-版本:   4.0.30319 X-Powered-By:ASP.NET日期:星期四,2017年5月25日16:00:44 GMT内容类型:application / json; charset = utf-8到期:-1   内容长度:36}}

我不知道自己做错了什么。有人可以帮忙吗?

类型:

class EmailFiles
{
    public string docNumber { get; set; }
    public EmailFileTypes.EmailFileType type { get; set; }
}

请求:

        List<EmailFiles> files = new List<EmailFiles>();

        if (chkShipping.IsToggled)
        {
            EmailFiles file = new EmailFiles();
            file.type = EmailFileTypes.EmailFileType.CustomerFile;
            file.docNumber = Helpers.GlobalVariables.gSOLookup.PackList;
            files.Add(file);
        }
        if (chkClosed.IsToggled)
        {
            EmailFiles file = new EmailFiles();
            file.type = EmailFileTypes.EmailFileType.ClosedFile;
            file.docNumber = Helpers.GlobalVariables.gSOLookup.Invoice;
            files.Add(file);
        }
        if (chkInvoice.IsToggled)
        {
            EmailFiles file = new EmailFiles();
            file.type = EmailFileTypes.EmailFileType.Invoice;
            file.docNumber = Helpers.GlobalVariables.gSOLookup.Invoice;
            files.Add(file);
        }

        string url = SetUrls.urlMtApi + "/api/EmailFile/?emailAddresses=" + strEmails;

        string strJson = JsonConvert.SerializeObject(files);
        //Results in: "[{\"docNumber\":\"234273\",\"type\":1},{\"docNumber\":\"633007\",\"type\":2}]" - which works in Postman!!

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

        HttpClient httpClient = new HttpClient();
        HttpResponseMessage response = await httpClient.PostAsync(url, content);

网络服务:

[System.Web.Http.HttpPost]
public string EmailFile([FromBody]string jsonfiles, [FromUri] string emailAddresses)
    {
        List<EmailFiles> files = JsonConvert.DeserializeObject<List<EmailFiles>>(jsonfiles);
        ...
    }

1 个答案:

答案 0 :(得分:2)

无需手动反序列化json主体,只需让模型绑定器通过使用正确的参数为您完成:

[System.Web.Http.HttpPost]
public MyModelReturnType EmailFile([FromBody] List<EmailFiles> files, [FromUri] string emailAddresses)
{
     // the framework has already deserialized the json request for you
}

如果您使用string而不是参数的真实模型,服务器将无法将您的请求正文绑定到它,因为它会期望JSON 字符串(包围双引号"),这可能会导致模型绑定异常,从而导致客户端出现500错误。

对于返回类型也是如此,只需使用您希望客户端接收的任何类作为返回类型,如果要将其发送给Json,则不要使用string