控制器调用另一个控制器C#的WebAPI [英] Controller invoking another controller C# WebApi

查看:537
本文介绍了控制器调用另一个控制器C#的WebAPI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制器,它需要援引另一控制器。我们在做客户端上的这项工作。我们要出于性能的考虑这样做服务器端。

I have a controller, it needs to invoke another controller. We WERE doing this work on the client. We want to do this server side for performance reasons.

请求是POST
请求URL = http://example.com/api/foo/1234567 (pretty标准的URL与绑定一个ID)

Request is a POST Request Url = "http://example.com/api/foo/1234567 (pretty standard url with binding for an id)

请求数据

{
  something1:'abc',
  something2:'def',
  copyFromUrl : '/api/bar/7654321'

};

的copyFromUrl可能是应用程序中的任何其他控制器。我不想用手卡住了一堆if语句上下堆叠做绑定。

The copyFromUrl could be any other controller in the application. I don't want to hand jam a bunch of if statements up and down the stack to do the binding.

更为复杂的问题是大多数控制器有三种不同的GET签名。
获取(刺ID)
获取(蜇ID,字符串的XPath)
获得()

Complicating the issue is most controllers have three different GET signatures. Get(sting id) Get(sting id, string xpath) Get()

推荐答案

这样做的一种方式,将基本短路的HttpServer和HttpClient的类。我在这里使用的ASP.NET Web API 2,但可以用原始的Web API使用相同的有希望的技术。

One way of doing this, would be to basically short-circuit HttpServer and HttpClient classes. I am using here ASP.NET Web API 2, but hopefully same technique can be used with original Web API.

下面是简约的工作样本:

Here is the minimalistic working sample:

public class BarController : ApiController
{

    // GET http://localhost/api/bar
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] {"Foo Bar", "Progress Bar"};
    }

    // GET http://localhost/api/bar?bar=Towel Bar
    [HttpGet]
    public IEnumerable<string> GetCustomBar(string bar)
    {
        return new string[] {"Foo Bar", "Progress Bar", bar};
    }

    // POST http://localhost/api/bar?action=/api/bar?bar=Towel Bar
    [HttpPost]
    public HttpResponseMessage StartAction(string action)
    {
        var config = new HttpConfiguration();
        WebApiConfig.Register(config);
        var server = new HttpServer(config);
        var client = new HttpClient(server);
        var response = client.GetAsync("http://localhost/" + action).Result;
        return response;
    }

正如你可以在这里看到,前两个动作中的参数不同,第三个动作接受URL(如code为例),允许它来调用任何其他操作。

As you can see here, the first two actions differ in parameters, the third action accepts url (as in code example) that allows it to invoke any other action.

我们基本上都在举办内存的服务器,应用我们的真实服务器具有相同的路线,然后立即查询它。

We are basically hosting a server in memory, applying same routes our real server has, and then immediately querying it.

硬codeD 本地主机实际上是没有使用运行时间,路线忽略它,但我们需要有效的绝对URL名称为内部验证通过。

Hard-coded localhost is actually not used run-time, the routes ignore it, but we need valid absolute URL name for the internal validation to pass.

这code只是一个例子,证明了概念,如果你可能。

This code is just an illustration, proof-of-concept if you may.

这篇关于控制器调用另一个控制器C#的WebAPI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆