我很难在同一控制器内调用函数。
这是我调用GetToken函数的函数
[HttpPost]
public ActionResult FileLoad()
{
using (var reader = new StreamReader("C:\\somedirectory\\Payout.csv"))
using (var csv = new CsvReader(reader))
{
csv.Configuration.RegisterClassMap<FundTransferMap>();
var json = JsonConvert.SerializeObject(csv.GetRecords<FundTransfer>());
//Response.Write(json);
TempData["FileJson"] = json;
return RedirectToAction("GetToken");
}
}
这是第一个函数应该调用的函数
[HttpPost]
private async Task<ActionResult> GetToken()
{
var client = new HttpClient();
var httpRequestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri("https://some-url.com//token"),
Headers = {
//{ HttpRequestHeader.Authorization.ToString(), "Bearer xxxxxxxxxxxxxxxxxxxx" },
{ HttpRequestHeader.Accept.ToString(), "application/json" },
{ HttpRequestHeader.ContentType.ToString(), "application/x-www-form-urlencoded"},
{ "client-id", "client-id"},
{ "client-secret","client-secret"},
{ "partner-id","partner-id"},
{ "X-Version", "1" }
},
Content = new FormUrlEncodedContent(new Dictionary<string, string>
{
{ "client_id", "clientid" },
{ "grant_type", "password" },
{ "username", "username" },
{ "password", "p@ssw0rd" },
{ "scope", "scope" }
})
};
var response = client.SendAsync(httpRequestMessage).Result;
var payload = JObject.Parse(await response.Content.ReadAsStringAsync());
TempData["accessToken"] = payload.Value<string>("access_token");
}
return View();
但是此代码在运行时会产生错误,因为它是一个àsync
函数,我也不希望第二个函数返回某些内容。
答案 0 :(得分:1)
我建议重写您的GetToken()
方法以将令牌作为字符串返回。
private async Task<string> GetToken()
{
var client = new HttpClient();
// removed code for clarity
var response = client.SendAsync(httpRequestMessage).Result;
var payload = JObject.Parse(await response.Content.ReadAsStringAsync());
var token = payload.Value<string>("access_token");
return Task.FromResult(token);
}
然后,您可以从需要获取令牌的任何其他控制器方法中轻松调用此方法:
[HttpPost]
public ActionResult FileLoad()
{
// removed code for clarity
// call method GetToken();
var token = await GetToken();
}