【问题标题】:Consume external Web API in MVC .Net在 MVC .Net 中使用外部 Web API
【发布时间】:2021-09-29 11:02:01
【问题描述】:

我需要使用外部 Web API,以便可以搜索和查看 GRID 格式的数据。

到目前为止,这是我的代码:

***Model***

public class AlertMessage
{
    public string Title { get; set; }
    public string Message { get; set; }
    public string Severity { get; set; }
}

public class ItemLine
{
    public string Description { get; set; }
    public int BilledAmount { get; set; }
    public int PaidAmount { get; set; }
}

public class CitationDetail
{
    public string CitationNumber { get; set; }
    public string DefendantName { get; set; }
    public string DateofBirth { get; set; }
    public string VehicleTagNumber { get; set; }
    public string CaseType { get; set; }
    public string CaseStatus { get; set; }
    public string AppearanceDate { get; set; }
    public bool IsPayable { get; set; }
    public int FineSuspended { get; set; }
    public int FineServed { get; set; }
    public List<AlertMessage> AlertMessages { get; set; }
    public List<ItemLine> ItemLines { get; set; }
}

public class Root
{
    public List<CitationDetail> CitationDetails { get; set; }
    public int CitationCount { get; set; }
    public bool SuccessfulSearch { get; set; }
    public string ErrorMessage { get; set; }
}

**Controller**

    string Baseurl = "http://10.241.2.68:8109/";
    public async Task<ActionResult> Index()
    {
        List<CitationDetail> CitInfo = new List<CitationDetail>();
        using (var client = new HttpClient())
        {
            //Passing service base url
            client.BaseAddress = new Uri(Baseurl);
            client.DefaultRequestHeaders.Clear();
            //Define request data format
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
           
            HttpResponseMessage Res = await client.GetAsync("api/Juris/Citation/7082^");
            //Checking the response is successful or not which is sent using HttpClient
            if (Res.IsSuccessStatusCode)
            {
                //Storing the response details recieved from web api
                var EmpResponse = Res.Content.ReadAsStringAsync().Result;
      //Deserializing the response recieved from web api and storing into the citation list
                CitInfo = JsonConvert.DeserializeObject<List<CitationDetail>>(EmpResponse);
            }
            //returning the citation list to view
            return View(CitInfo);
        }
    }

我目前收到此错误:


无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型 'System.Collections.Generic.List`1[CPA.Models.CitationDetail]' 因为该类型需要 JSON 数组(例如[1,2,3]) 正确反序列化。 要修复此错误,要么将 JSON 更改为 JSON 数组(例如 [1,2,3]),要么将反序列化类型更改为普通的 .NET 类型(例如,不是像整数这样的原始类型,而不是像这样的集合类型可以从 JSON 对象反序列化的数组或列表。 JsonObjectAttribute 也可以添加到类型中以强制它从 JSON 对象反序列化。 路径“CitationDetails”,第 1 行,位置 19。

 ***JSON*****
{
"CitationDetails": [
    {
        "CitationNumber": "00000708244",
        "DefendantName": ",  ",
        "DateofBirth": "",
        "VehicleTagNumber": "",
        "CaseType": "CITATION",
        "CaseStatus": "",
        "AppearanceDate": "",
        "IsPayable": true,
        "FineSuspended": 0,
        "FineServed": 0,
        "AlertMessages": [],
        "ItemLines": [
            {
                "Description": "Fine Amount",
                "BilledAmount": 0,
                "PaidAmount": 0
            }
        ]
    }
],
"CitationCount": 1,
"SuccessfulSearch": true,
"ErrorMessage": ""

}

【问题讨论】:

  • 至少需要显示 api/Juris/Citation action 或 json 输出
  • 你好 - 我添加了 JSON - 此时我需要搜索机制方面的帮助 - 感谢您的帮助 - 我是这个 API 数据 Web 视图的新手 - 在此先感谢!
  • 很抱歉,您对搜索机制是什么意思。您能否在您的问题中加入一些解释,或者最好创建另一个问题。
  • 我需要在我的页面顶部有一个搜索过滤器。过滤从 GET 调用返回的数据。
  • 我认为您应该为它创建另一个帖子。 Stackoverlow 有一个规则——一次一个问题。搜索条件通常使用 Get Api 作为输入参数发送。通常没有人在得到结果后使用它们进行搜索。请再考虑一下。

标签: c# json asp.net-web-api model-view-controller


【解决方案1】:

我看不到你的输出 json 文件,所以我最好的猜测是替换

   var EmpResponse = Res.Content.ReadAsStringAsync().Result;
 CitInfo = JsonConvert.DeserializeObject<List<CitationDetail>>(EmpResponse);

通过

 var empResponse = await Res.Content.ReadAsStringAsync();
var empResponseObj = JsonConvert.DeserializeObject<Root>(empResponse);
 .......

 return View(empResponseObj.CitationDetails);

【讨论】:

  • 太棒了! - 这行得通!现在我需要能够搜索已返回的这些数据。对此的任何帮助将不胜感激!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-18
  • 1970-01-01
  • 2021-12-04
  • 2021-06-09
  • 1970-01-01
  • 2021-07-17
  • 1970-01-01
相关资源
最近更新 更多