asp.net-mvc ASP.NET MVC 4 应用程序调用远程 WebAPI

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13200381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 02:23:17  来源:igfitidea点击:

ASP.NET MVC 4 Application Calling Remote WebAPI

asp.net-mvcasp.net-mvc-4asp.net-web-api

提问by Glenn Arndt

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).

我过去创建了几个 ASP.NET MVC 应用程序,但我以前从未使用过 WebAPI。我想知道如何创建一个简单的 MVC 4 应用程序,该应用程序通过 WebAPI 而不是通过普通的 MVC 控制器执行简单的 CRUD 操作。诀窍是 WebAPI 应该是一个单独的解决方案(事实上,很可能在不同的服务器/域上)。

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.

我怎么做?我错过了什么?是否只是设置指向 WebAPI 服务器的路由的问题?我发现的所有展示如何使用 MVC 应用程序使用 WebAPI 的示例似乎都假设 WebAPI 已“嵌入”到 MVC 应用程序中,或者至少在同一台服务器上。

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.

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

回答by tugberk

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.

您应该使用新的 HttpClient 来使用您的 HTTP API。我还可以建议您使您的调用完全异步。由于 ASP.NET MVC 控制器操作支持基于任务的异步编程模型,因此它非常强大且简单。

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

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

然后,我可以通过我的 MVC 控制器异步使用它,如下所示:

public class HomeController : Controller {

    private CarRESTService service = new CarRESTService();

    public async Task<ActionResult> Index() {

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

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

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

My Take on Task-based Asynchronous Programming in C# 5.0 and ASP.NET MVC Web Applications

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

回答by Glenn Arndt

Thanks everyone for the responses. @tugberk led me down the right path, I think. This worked for me...

感谢大家的回应。@tugberk 带我走上了正确的道路,我想。这对我有用...

For my CarsRESTService helper:

对于我的 CarsRESTService 助手:

public class CarsRESTService
{
    readonly string baseUri = "http://localhost:9661/api/cars/";

    public List<Car> GetCars()
    {
        string uri = baseUri;
        using (HttpClient httpClient = new HttpClient())
        {
            Task<String> response = httpClient.GetStringAsync(uri);
            return JsonConvert.DeserializeObjectAsync<List<Car>>(response.Result).Result;
        }
    }

    public Car GetCarById(int id)
    {
        string uri = baseUri + id;
        using (HttpClient httpClient = new HttpClient())
        {
            Task<String> response = httpClient.GetStringAsync(uri);
            return JsonConvert.DeserializeObjectAsync<Car>(response.Result).Result;
        }
    }
}

And then for CarsController.cs:

然后对于 CarsController.cs:

public class CarsController : Controller
{
    private CarsRESTService carsService = new CarsRESTService();

    //
    // GET: /Cars/

    public ActionResult Index()
    {
        return View(carsService.GetCars());
    }

    //
    // GET: /Cars/Details/5

    public ActionResult Details(int id = 0)
    {
        Car car = carsService.GetCarById(id);

        if (car == null)
        {
            return HttpNotFound();
        }
        return View(car);
    }
}

回答by peco

You can use WCF to consume the service. Like so:

您可以使用 WCF 来使用该服务。像这样:

[ServiceContract]
public interface IDogService
{
    [OperationContract]
    [WebGet(UriTemplate = "/api/dog")]
    IEnumerable<Dog> List();
}

public class DogServiceClient : ClientBase<IDogService>, IDogService
{
    public DogServiceClient(string endpointConfigurationName) : base(endpointConfigurationName)
    {
    }

    public IEnumerable<Dog> List()
    {
        return Channel.List();
    }
}

And then you can consume it in your controller:

然后你可以在你的控制器中使用它:

public class HomeController : Controller
{
    public HomeController()
    {
    }

    public ActionResult List()
    {
        var service = new DogServiceClient("YourEndpoint");
        var dogs = service.List();
        return View(dogs);
    }
}

And in your web.config you place the configuration for your endpoint:

并在您的 web.config 中放置端点的配置:

<system.serviceModel>
  <client>
    <endpoint address="http://localhost/DogService" binding="webHttpBinding"
    bindingConfiguration="" behaviorConfiguration="DogServiceConfig" 
    contract="IDogService" name="YourEndpoint" />
  </client>
  <behaviors>
    <endpointBehaviors>
      <behavior name="DogServiceConfig">
        <webHttp/>
      </behavior>
    </endpointBehaviors>
  </behaviors>
</system.serviceModel>

回答by Onur Topal

http://restsharp.org/is the answer to your questions. I am currently using it in an application which has similar structure.

http://restsharp.org/是您问题的答案。我目前正在一个具有类似结构的应用程序中使用它。

But more generally using WebAPI is just posting and requesting data how to process is up to you. You can even use standard WebRequest and JavascriptSerializer.

但更普遍的是,使用 WebAPI 只是发布和请求数据,如何处理取决于您。您甚至可以使用标准的 WebRequest 和 JavascriptSerializer。

Cheers.

干杯。

回答by cuongle

In this case, you can use HttpClientto consume Web API from your controller.

在这种情况下,您可以使用HttpClient从您的控制器使用 Web API。