在MVC 6中消费REST服务

4
我需要帮助。我正在创建一个MVC 6应用程序,但无法理解如何从REST服务中使用JSON。我找不到连接我的项目和服务然后消耗它的方法。在之前的版本中,无法添加服务引用。我在ASP.NET 5文档中找不到有关在MVC 6中使用第三方服务的政策。请问是否有人遇到相同问题?
2个回答

5
要从MVC中的RESTful服务获取JSON,只需向服务API发出http调用,并使用包含json属性的模型解析响应。您可以在这里阅读更多相关信息: http://bitoftech.net/2014/11/18/getting-started-asp-net-5-mvc-6-web-api-entity-framework-7/ 以下是示例:
        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;
            }

        }

3
在ASP.NET中,没有像WSDL描述的那样针对REST服务的“添加服务引用”功能。从来没有过。您可以像在浏览器中直接使用javascript一样使用服务。不同之处在于,您需要使用任何http客户端(HttpClient或RestSharp最受欢迎)在.NET中编写类似的代码。
有一些努力使REST服务更易于使用。Swagger是我用来描述我的API的工具。它还允许为各种语言生成客户端代码。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接