我知道这个错误
InvalidCastException:无法将“令牌”类型的对象强制转换为“Microsoft.AspNetCore.Mvc.IActionResult”
我做错什么了吗?我对编程很陌生,这是我第一次实习。我原以为这会是小菜一碟,但几天来我一直在做研究,试图在C# .NET 6中建立一个身份验证流(Auth2.0)
我只是现在太累了,我很感激你的帮助.我有客户身份,客户机密和客户签名。
using Newtonsoft.Json;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using WebApplication1.Models;
using RestSharp;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Configuration;
using System;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;
using static System.Net.Mime.MediaTypeNames;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web;
public async Task<IActionResult> Index()
{
using (var httpClient = new HttpClient())
{
string baseAddress = "https://auth.monday.com/oauth2/token";
string grant_type = "client_credentials";
string client_id = "id";
string client_secret = "secret";
var clientCreds = System.Text.Encoding.UTF8.GetBytes($"{client_id}:{client_secret}");
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Basic", System.Convert.ToBase64String(clientCreds));
var form = new Dictionary<string, string>
{
{"grant_type", grant_type}
};
HttpResponseMessage tokenResponse = await httpClient.PostAsync(baseAddress, new FormUrlEncodedContent(form));
var jsonContent = await tokenResponse.Content.ReadAsStringAsync();
Token tok = JsonConvert.DeserializeObject<Token>(jsonContent);
return (IActionResult)tok;
}
return View();
}发布于 2022-09-18 03:33:31
我不太清楚你在阅读你的问题和代码后想要做什么,但你已经被告知了原因。运行时不能将“令牌”类型转换为IActionResult类型。
您应该在MS中查找InvalidCastException,以更好地理解转换是如何工作的。
当您返回'( IActionResult ) tok‘时,不能强迫tok成为IActionResult。
发布于 2022-09-18 05:10:12
tok对象不是从IActionResult继承的,所以您要获得InvalidCastException。
将tok作为视图数据传递
using System.Threading.Tasks;
using System.Web;
public async Task<IActionResult> Index()
{
using (var httpClient = new HttpClient())
{
string baseAddress = "https://auth.monday.com/oauth2/token";
string grant_type = "client_credentials";
string client_id = "id";
string client_secret = "secret";
var clientCreds = System.Text.Encoding.UTF8.GetBytes($"{client_id}:{client_secret}");
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Basic", System.Convert.ToBase64String(clientCreds));
var form = new Dictionary<string, string>
{
{"grant_type", grant_type}
};
HttpResponseMessage tokenResponse = await httpClient.PostAsync(baseAddress, new FormUrlEncodedContent(form));
var jsonContent = await tokenResponse.Content.ReadAsStringAsync();
Token tok = JsonConvert.DeserializeObject<Token>(jsonContent);
ViewData["token"] = tok ;
return View();
}
return View();
}在索引视图中,使用
@{ var token = ViewData["token"] as Token;}https://stackoverflow.com/questions/73759808
复制相似问题