I need help. I am creating an MVC 6 application and stuck on the part where I should consume JSON from a REST service. I could not find the way I should connect my project to the service and then consume it.
There is no way to add service reference as in previous versions and I could not find it ASP.NET 5 documentation where the policy for using 3rd party services in MVC 6 is regulated. Did someone had the same issue?
To get the JSON from RESTful service in MVC you just make a http call to the service API and parse the response with model that contains the properties of the json. You can read more about that here: http://bitoftech.net/2014/11/18/getting-started-asp-net-5-mvc-6-web-api-entity-framework-7/
An example would look like something like this:
public YourModel MakeRequest(string requestUrl)
{
try
{
HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
{
throw new Exception(String.Format("Server error (HTTP {0}: {1}).", response.StatusCode, response.StatusDescription));
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
var responseObject = serializer.Deserialize<YourModel>(response);
return responseObject;
}
}
catch (Exception e)
{
// catch exception and log it
return null;
}
}
There is no "add a service reference" feature for REST services in ASP.NET (like it is for WSDL described ones). There never was. You consume the service as you would consume it directly from your browser using javascript. The difference is that you need to write similar code in .NET using any http client (HttpClient or RestSharp are the most popular).
There are some efforts to make the REST services easier to consume. Swagger is the tool I use to describe my API. It also allows to generate client code for various languages.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With