c# - 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
}
解决方案
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?
推荐阅读
- apache - 如何在 Apache php 中启用 sqlite
- mysql - 数据表 - 有两个条件
- javascript - Popper 不坚持滚动上的 ref 元素
- google-cloud-platform - 增加已配置 GCP Cloud Shell 虚拟机的磁盘大小
- java - 使用一些数组和循环的简化策划游戏
- c++ - C++ 类的大小是 40 字节而不是 36
- python - 绘制作为其他 2 列 matplotlib 的红利的数据
- java - (Java 12)当库作为插件加载时 JAXB 不起作用
- angular - 我应该在哪里存储 CSS 文件以在我的 monorepo 中跨应用程序和库使用?
- python - 如何计算从现在到某个时间的小时数