简体   繁体   English

在 MVC .Net 中使用外部 Web API

[英]Consume external Web API in MVC .Net

I need to consume an external Web API so I can Search and View the data in a GRID format.我需要使用外部 Web API,以便以 GRID 格式搜索和查看数据。

So far here is my code:到目前为止,这是我的代码:

***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);
        }
    }

I'm currently getting this error:我目前收到此错误:


Cannot deserialize the current JSON object (eg {"name":"value"}) into type 'System.Collections.Generic.List`1[CPA.Models.CitationDetail]' because the type requires a JSON array (eg [1,2,3]) to deserialize correctly.无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型“System.Collections.Generic.List`1[CPA.Models.CitationDetail]”,因为该类型需要一个 JSON 数组(例如 [1, 2,3]) 以正确反序列化。 To fix this error either change the JSON to a JSON array (eg [1,2,3]) or change the deserialized type so that it is a normal .NET type (eg not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object.要修复此错误,请将 JSON 更改为 JSON 数组(例如 [1,2,3])或更改反序列化类型,使其成为正常的 .NET 类型(例如,不是像整数这样的原始类型,而不是像这样的集合类型)可以从 JSON 对象反序列化的数组或列表)。 JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. JsonObjectAttribute 也可以添加到类型中以强制它从 JSON 对象反序列化。 Path 'CitationDetails', line 1, position 19.路径“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": ""

} }

在此处输入图片说明

I can' t see your output json file, so my best guess will be replacing我看不到你的输出 json 文件,所以我最好的猜测是替换

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

by经过

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

 return View(empResponseObj.CitationDetails);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM