且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

控制器调用另一个控制器C#的WebAPI

更新时间:2021-06-28 22:55:34

这样做的一种方式,将基本短路的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.