首页 > 解决方案 > ASP.NET Web API - HttpClient.PostAsync 本地 API 不会进入代码

问题描述

所以这是我的情况...

我有一个单元测试项目,其中我实例化了一个 Web API 控制器。单元测试项目和 ASP.NET Web API 项目都在同一个解决方案中。Web API 控制器的实现包括将 HttpClient.PostAsync 调用到另一个解决方案中并部署到本地 IIS 的另一个 Web API 的部分。

调用方方法的项目和部署到 IIS 的项目都在 Visual Studio 中打开(打开了 2 个 VS 窗口)。我已经将 pdb 和所有从部署到 IIS 的解决方案复制到单元测试项目的 bin/debug 文件夹中。

但是每次控件转到 PostAsync 调用时,当我按下 F11 时,它都不会进入在另一个 VS 编辑器中打开的代码。

我可以知道我将如何实现这一目标吗?

单元测试项目:

[TestMethod]
public void TestController
{
TestController t = new TestController();
t.Get();
}

测试控制器:

[HttpPost]
public ActionResult Get()
{

//assume that HttpClient.BaseAddress was already set in constructor

client.PostAsync("/testapi/getdata");
}

另一个解决方案中的控制器,部署在 IIS 中

[Route("testapi/getdata")]
[HttpPost]
public ActionResult Get()
{
//implementation here
}

标签: c#asp.netasp.net-coreasp.net-web-api

解决方案


The problem is that you are calling the API using Post, but your Api is accepting only Get

client.PostAsync("/testapi/getdata");

///Controller in another solution, deployed in IIS

[Route("testapi/getdata")]
[HttpGet]
public ActionResult Get()

you have to change client.GetAsync maybe or you can use post but change api.

and when you use async you have to use await or Result, but await is preferable

 awant client.GetAsync("/testapi/getdata")
//or
client.GetAsync("/testapi/getdata").Result;

///Controller in another solution, deployed in IIS

[Route("testapi/getdata")]
[HttpGet]
public ActionResult Get()

// but should be
public async Task<ActionResult> Get()

UPDATE

you have updated your question, but after this it looks even more strange

[Route("testapi/getdata")]
[HttpPost]
public ActionResult Get()

for getdata without any input parameters and null request body you select HttpPost.

client.PostAsync("/testapi/getdata");

It will not be even compiled, since post needs content.

I am wondering what is API controller like. Does it have an attribute route too? Or all your code is just a fake?


推荐阅读