问题描述
我有一个名为 async
的 GetDetails();
方法来从 API 获取数据。
public async Task<string> GetDetails(string token,int tenantId,string fromDate,string searchText)
{
try
{
string serviceUrl = "http://localhost/Testapi/api/details/requestDetails/Details";
//API callimg code going here....
var response = await client.PostAsync(serviceUrl,content);
var result = await response.Content.ReadAsstringAsync();
client.dispose();
return result;
}
}
我需要获得高于 async
的方法数据。所以我尝试按如下方式进行,
public string GetAllDetails(string token,string searchText)
{
var dataResult = GetDetails(token,tenantId,fromDate,searchText);
return dataResult;
}
但我无法从非异步方法调用 GetDetails
异步方法。有没有其他方法可以做到这一点?我可以将该 GetAllDetails()
方法设为异步,因为它从 Web 方法调用如下。
[WebMethod(EnableSession = true)]
public string GetDetails(string fromDate,string searchText)
{
try
{
SessionState session = new SessionState(Session);
DetialsConfiguration dc = new DetialsConfiguration();
string details = dc.GetAllDetails(session.JwtToken,session.ClientId,searchText);
return details;
}
catch (Exception ex)
{
Logger.LogErrorEvent(ex);
throw;
}
}
如何获取 GetDetails()
API 响应数据到我的网络方法?请帮我做这件事?
解决方法
如何从非异步方法获取异步方法值
您不会...除非您有一个非常具体的用例。相反,你让 async 和 await 模式传播
public async Task<string> GetAllDetails(string token,int tenantId,string fromDate,string searchText)
{
var dataResult = await GetDetails(token,tenantId,fromDate,searchText);
return dataResult;
}
...
[WebMethod(EnableSession = true)]
public async Task<string> GetDetails(string fromDate,string searchText)
{
try
{
SessionState session = new SessionState(Session);
DetialsConfiguration dc = new DetialsConfiguration();
string details = await dc.GetAllDetails(session.JwtToken,session.ClientId,searchText);
return details;
}
catch (Exception ex)
{
Logger.LogErrorEvent(ex);
throw;
}
}
另请注意,任何 async
方法都应具有异步后缀,例如 GetAllDetailsAsync