Use REST service in MVC 6

I need help. I am creating an MVC 6 application and stick to the part where I have to use JSON from the REST service. I could not find a way to connect my project to the service, and then use it.

It is impossible to add a link to the service, as in previous versions, and I could not find its ASP.NET 5 documentation, which regulates the policy of using third-party services in MVC 6. Did someone have the same problem?

+4
source share
2 answers

To get JSON from a RESTful service in MVC, you simply make an http call to the API service and parse the response using a model that contains json properties. You can learn more about this here: http://bitoftech.net/2014/11/18/getting-started-asp-net-5-mvc-6-web-api-entity-framework-7/

An example would look 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;
            }

        }
+5
source

There is no “add service” function for REST services in ASP.NET (for example, for the described WSDLs). It never happened. You consume the service as you will 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).

, REST. Swagger - , API. .

+3

Source: https://habr.com/ru/post/1606725/


All Articles