我有一个ASP。. NET Core MVC和Web API项目
当我尝试将项目信息发送到API时发生此错误(当然API工作正常,我不认为有问题):
我的代码是:UnsupportedMediaTypeException: No MediaTypeFormatter is available to read "TokenModel"text/plain对象媒体内容。
public class TokenModel
{
public string Token { get; set; }
}
在AuthController
中,我有:
var _Client = _httpClientFactory.CreateClient("MyApiClient");
var jsonBody = JsonConvert.SerializeObject(login);
var content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
var response = _Client.PostAsync("/Api/Authentication", content).Result;
if (response.IsSuccessStatusCode)
{
var token = response.Content.ReadAsAsync<TokenModel>().Result;
}
错误发生在这一行:
var token = response.Content.ReadAsAsync<TokenModel>().Result;
HomeController
:
public IActionResult Index()
{
var token = User.FindFirst("AccessToken").Value;
return View(_user.GetAllUsers(token));
}
UserRepository
:
public List<UserViewModel> GetAllUsers(string token)
{
_client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
var res = _client.GetStringAsync(UrlMyApi).Result;
List<UserViewModel> users = JsonConvert.DeserializeObject<List<UserViewModel>>(res);
return users;
}
您的API正在返回text/plain
的内容类型,并且没有ReadAsAsync<string>()
将尝试使用的默认媒体类型格式化程序(MediaTypeFormatter
)支持原样解析。它们使用JSON/XML。有几种方法,但最简单的可能是将内容读取为字符串,并在
var tokenJSON = response.Content.ReadAsStringAsync().Result;
var token = JsonConvert.DeserializeObject<TokenModel>(tokenJSON);
同样,当你使用Async时方法,你应该返回Task
从你的行动和await
的结果,而不是使用.Result
,因为你只是创建开销当前。
var tokenJSON = await response.Content.ReadAsStringAsync();
var token = JsonConvert.DeserializeObject<TokenModel>(tokenJSON);