繁体   English   中英

在控制台应用程序中使用Api

[英]Consuming Api in Console Application

我正在尝试使用控制台应用程序使用我的api,但出现异常。 当我尝试将JSON数据放入模型时,以下是以下例外:

引发的异常:mscorlib.dll中的'Newtonsoft.Json.JsonSerializationException'引发的异常:mscorlib.dll中的'System.AggregateException'引发的异常:ConsoleApplication1.exe中的'Newtonsoft.Json.JsonSerializationException'

我的源代码:

class Program
{
    public class IndividualModel
    {
        public string PayorCode { get; set; }
        public string Adminlvl { get; set; }
        public string LvlDesc { get; set; }
    }

    static void Main(string[] args)
    {
        HttpClient cons = new HttpClient();
        cons.BaseAddress = new Uri("http://localhost:52505/");
        cons.DefaultRequestHeaders.Accept.Clear();
        cons.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

        try
        {
            MyAPIGet(cons).Wait();
        }
        catch (AggregateException e)
        {
            try
            {
                throw e.GetBaseException();
            }
            catch (Exception ea)
            {
                //throw ea.InnerException;
                Console.WriteLine(ea.ToString());
            }
        }
    }

    static async Task MyAPIGet(HttpClient cons)
    {
        using (cons)
        {
            HttpResponseMessage res = await cons.GetAsync("api/PayorPortal/GetPayorUserLevel?payorCode=STARCAR&adminlvl=1");
            res.EnsureSuccessStatusCode();
            if (res.IsSuccessStatusCode)
            {
                IndividualModel tag = await res.Content.ReadAsAsync<IndividualModel>();
                Console.WriteLine("\n");
                Console.WriteLine("---------------------Calling Get Operation------------------------");
                Console.WriteLine("\n");
                Console.WriteLine("tagId tagName tagDescription");
                Console.WriteLine("-----------------------------------------------------------");
                Console.WriteLine("{0}\t{1}\t\t{2}", tag.Adminlvl, tag.LvlDesc, tag.PayorCode);
                Console.ReadLine();
            }
        }
    }
  }
}

这是json数据

“[{\\” PayorCode \\ “:\\” STARCAR \\”,\\ “Adminlvl \\”:\\ “1 \\” \\ “LvlDesc \\”:\\ “管理员\\”},{\\ “PayorCode \\” :\\“ STAR‌CAR \\”,\\“ Adminlvl \\”:\\ ‌“ 2 \\”,\\“ LvlDesc \\”:\\“ Sytemtem Admin \\”},{\\“ PayorCode \\”:\\\\ STARCAR \\ “,\\” Adminlvl \\“:\\” 3 \\“,\\” Lvl‌Desc \\“:\\”系统用户\\“}]”

当您获取JSON数据时,请检查您是获取单个数据还是列表。 之所以收到此Newtonsoft.Json.JsonSerializationException是因为您无法将JSON数据映射到Model,因为您将其映射到IndividualModel

我的建议是您在GetAsync()之后GetAsync()添加一个断点,然后检查它是否为列表。 如果是,则更改此行:

IndividualModel tag = await res.Content.ReadAsAsync<IndividualModel>();

对此:

List<IndividualModel> tag = await res.Content.ReadAsAsync<List<IndividualModel>>();

希望能帮助到你!

暂无
暂无

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

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