加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-web-api – 如何从WEB API检索邮件?

发布时间:2020-12-16 00:29:37 所属栏目:asp.Net 来源:网络整理
导读:我创建了一些Web apis,当发生错误时,api返回使用CreateErrorResponse消息创建的HttpResponseMessage。这样的事情 return Request.CreateErrorResponse( HttpStatusCode.NotFound,"Failed to find customer."); 我的问题是,我无法弄清楚消费者应用程序中的
我创建了一些Web apis,当发生错误时,api返回使用CreateErrorResponse消息创建的HttpResponseMessage。这样的事情
return Request.CreateErrorResponse(
              HttpStatusCode.NotFound,"Failed to find customer.");

我的问题是,我无法弄清楚消费者应用程序中的消息(在这种情况下是“找不到客户”)。

以下是消费者样本:

private static void GetCustomer()
{
    var client = new HttpClient();
    client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));
    string data =
        "{"LastName": "Test","FirstName": "Test"";

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

    var httpResponseMessage = 
                 client.PostAsync(
                    new Uri("http://localhost:55202/api/Customer/Find"),content).Result;
    if (httpResponseMessage.IsSuccessStatusCode)
    {
        var cust = httpResponseMessage.Content.
                  ReadAsAsync<IEnumerable<CustomerMobil>>().Result;
    }
}

任何帮助是极大的赞赏。

解决方法

确保您适当地设置了accept和或者内容类型(解析请求内容时可能有500个错误的来源):
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

content.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json");

那你可以做:

var errorMessage = response.Content.ReadAsStringAsync().Result;

当然这是客户端。 WebApi应根据接受和/或内容类型适当处理内容的格式。好奇,你也可以抛出新的HttpResponseException(“找不到客户”),HttpStatusCode.NotFound);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读