本文介绍了ASP.NET MVC 4应用程序中调用远程的WebAPI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经建立在过去的几个ASP.NET MVC应用程序,但我以前从未使用过WebAPIs。我想知道我怎么能创建一个简单的MVC 4应用程序,通过的WebAPI,而不是通过正常的MVC控制器执行简单的CRUD的东西。诀窍在于的WebAPI应该是一个独立的解决方案(,事实上,很可能是在不同的服务器/域)。

I've created a couple ASP.NET MVC applications in the past, but I've never used WebAPIs before. I'm wondering how I could create a simple MVC 4 app that does simple CRUD stuff via WebAPI instead of through a normal MVC controller. The trick is that the WebAPI should be a separate solution (and, in fact, could very well be on a different server/domain).

我该怎么办呢?我在想什么?难道仅仅是一个设置路由指向的WebAPI的服务器的事情?我发现展示了如何使用消费MVC应用程序WebAPIs所有的例子似乎承担的WebAPI被烤到MVC应用程序,或者至少是在同一台服务器上。

How do I do that? What am I missing? Is it just a matter of setting up routes to point to the WebAPI's server? All the examples I've found showing how to consume WebAPIs using an MVC application seem to assume the WebAPI is "baked in" to the MVC application, or at least is on the same server.

哦,澄清一下,我不是在谈论Ajax调用使用jQuery ......我的意思是MVC应用程序的控制器应使用的WebAPI获取/放置数据。

Oh, and to clarify, I'm not talking about Ajax calls using jQuery... I mean that the MVC application's controller should use the WebAPI to get/put data.

推荐答案

您应该使用新的HttpClient来消耗你的HTTP的API。我还可以建议你让你的通话完全异步。由于ASP.NET MVC控制器行动支持基于任务的异步编程模型,它是pretty功能强大且易于。

You should use new HttpClient to consume your HTTP APIs. What I can additionally advise you to make your calls fully asynchronous. As ASP.NET MVC controller actions support Task-based Asynchronous Programming model, it is pretty powerful and easy.

下面是一个过于简单的例子。下面code是一个示例请求辅助类:

Here is an overly simplified example. The following code is the helper class for a sample request:

public class CarRESTService {

    readonly string uri = "http://localhost:2236/api/cars";

    public async Task<List<Car>> GetCarsAsync() {

        using (HttpClient httpClient = new HttpClient()) {

            return JsonConvert.DeserializeObject<List<Car>>(
                await httpClient.GetStringAsync(uri)
            );
        }
    }
}

随后,我可以消耗通过我的MVC控制器异步如下:

Then, I can consume that through my MVC controller asynchronously as below:

public class HomeController : Controller {

    private CarRESTService service = new CarRESTService();

    public async Task<ActionResult> Index() {

        return View("index",
            await service.GetCarsAsync()
        );
    }
}

您可以看看下面的帖子看到异步I的影响/在ASP.NET MVC O操作:

You can have a look at the below post to see the effects of asynchronous I/O operations with ASP.NET MVC:

My采取基于任务的异步编程在C#5.0和ASP.NET MVC Web应用程序

这篇关于ASP.NET MVC 4应用程序中调用远程的WebAPI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 07:11