【发布时间】:2020-12-02 23:07:49
【问题描述】:
我有一个 ASP.NET MVC 应用程序,我想从中使用 ASP.NET Web API REST 服务。 于是我找到了一段代码here。
在我的情况下,我想从我的 ASP.NET MVC 应用程序中的一个类中的方法调用 ASP.NET Web API 方法 (DumpIntoFile)(这个类不是控制器)。在对 DumpIntoFile 的调用完成并完成之前,我需要不继续执行。我该怎么做?我从未使用过 async 和 await,所以我完全不明白它们是如何工作的。
public void GetData()
{
Warehouse myData = new Warehouse();
myData.id = 1111;
myData.name = blabla;
string path = "c:\temp";
string filename = "myData.dat";
// Stuff here
this.DumpWarehouseDataIntoFile(myData, path, filename);
// Some other stuff here
}
public async void DumpWarehouseDataIntoFile(Warehouse myData, string path, string filename) // See Warehouse class later in this post
{
//Hosted web API REST Service base url
string Baseurl = "http://XXX.XXX.XX.X:YYYY/";
using (var client = new HttpClient())
{
//Passing service base url
client.BaseAddress = new Uri(Baseurl);
client.DefaultRequestHeaders.Clear();
//Define request data format
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Serialize parameter to pass to the asp web api rest service
string jsonParam = Newtonsoft.JsonConvert.SerializeObject(myData);
//Sending request to find web api REST service resource using HttpClient
// How can I pass parameters jsonParam, path and filename to below call??????? Concatenating it?
HttpResponseMessage Res = await client.GetAsync("api/Warehouse/DumpIntoFile");
//Checking the response is successful or not which is sent using HttpClient
if (Res.IsSuccessStatusCode)
{
// Some other sftuff here
}
}
}
仓库对象如下:
public class Warehouse {
public Warehouse();
public int id { get; set; }
public string name { get; set; }
// some other stuff here
}
以及带有方法的 web api 休息控制器:
public class MyWebApiController : ApiController
{
public bool DumpIntoFile(string data, string path, string filename)
{
bool result;
Warehouse myData = JsonConvert.DeserializeObject<Warehouse>(data);
string myPath = path;
string myFilename = filename;
// Here rest of code
return result;
}
}
我也想在下面做:
- 避免对 URL 进行硬编码,因为如果 ASP.NET Web API REST 服务将来在另一台服务器上发布,那么我需要修改代码,更改它并再次发布我的 ASP.NET MVC 应用程序。也许将网址放在 web.config 文件中并从那里读取?
- 如何将参数jsonParam、路径和文件名传递给web api rest服务?连接它?
注意事项: 我正在使用 NET 4.5 和 Visual Studio 2013。
【问题讨论】:
-
所以你的意思是
await client.GetAsync("api/Warehouse/DumpIntoFile");不等待方法调用完成?你是什么意思?DumpIntoFile中有什么内容? -
@Dave 我已经更新了我的帖子。关于等待 client.GetAsync 我现在正在实现它,但我还没有能够测试它。我想知道 await 是否会等待并且不会继续执行下一行代码,直到对 web api rest 服务的调用完成并完成。我说的对吗?
-
Ralph(对不起,我无法在@提及中得到你的名字)-好的,是的,这应该等待请求完成。每当您使用 Async 方法时,您都需要等待它们,否则执行将不会等待 Async 方法完成。测试
await client.GetAsync("api/Warehouse/DumpIntoFile");看看它是否在等待。如果您看到意外的输出,那么DumpIntoFile中会有一些未等待的内容@
标签: asp.net-mvc rest asp.net-web-api json.net dotnet-httpclient