ASP.NET MVC 4 应用程序调用远程 WebAPI

问题描述:

我过去创建了几个 ASP.NET MVC 应用程序,但我以前从未使用过 WebAPI.我想知道如何创建一个简单的 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 应用程序使用 WebAPI 的示例似乎都假设 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.

哦,澄清一下,我不是在谈论使用 jQuery 的 Ajax 调用......我的意思是 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 控制器操作支持基于任务的异步编程模型,因此它非常强大且简单.

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.

这是一个过于简化的例子.以下代码是示例请求的帮助程序类:

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()
        );
    }
}

您可以查看以下帖子以了解使用 ASP.NET MVC 进行异步 I/O 操作的效果:

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

我对 C# 5.0 和 ASP.NET MVC Web 应用程序中基于任务的异步编程的看法