Best Way To Consume JSON from REST API in .NET

2020-07-07 05:50发布

I'm working on a .net web app in c# and I need to consume a REST service from a third party (they are not using WCF). I'm coming from a background of using web service calls where there was a WSDL available and Visual Studio would build all of the underlying code and then I am ready to go.

Is there no tool or framework that can to some degree simulate this behavior? I understand that without a contract there is no way for a tool to know what to expect but I would think I could go through a wizard where I supply parameters to make a REST call and then help the wizard work out the details of the response. At the end of the process I would have a set of objects that model the REST API similar to how the web service behave.

I know that REST and JSON have some great advantages to them but the lack of a standard out of the box contract to allow automated code generation seems like a real step backwards.

Am I missing something obvious or is that just the current state of affairs when consuming REST in .NET? Do I really need to write boiler plate code for each new API?

标签: .net rest
2条回答
成全新的幸福
2楼-- · 2020-07-07 06:30

I would suggest looking at the WCF REST Starter Kit All up page.

Download here: WCF REST Starter Kit Preview 2

Documentation here: WCF Rest Starter Kit GUide Scroll down to 'Consuming RESTful Services with HttpClient'

You will end up using the ReadAsJasonDataContract e.g.

HttpResponseMessage resp = http.Get("friends_timeline.json");
resp.EnsureStatusIsSuccessful();
ProcessStatusesAsDataContract(resp.Content.ReadAsJsonDataContract<statusList>());

This looks to be a reasonable how-to How-2 on CodeProject

If you feel like being a bit more hands on and want to eek out more performance then doing your own web requests and using JSON.NET to handle the serialization is abnother good option. JSON.Net (Disclosing that JSON.Net is written by a colleague)

查看更多
虎瘦雄心在
3楼-- · 2020-07-07 06:34

You can look at using RestSharp to access the REST API. I gave a sample, including an approach at using AutoMapper to go from data transfer object to domain model on this SO question.

查看更多
登录 后发表回答