使用Visual Studio 2013我創建了一個新的Web API 2項目和一個新的MVC項目。將有其他客戶端訪問API,這是它創建的原因。最終API的客戶端將允許用戶使用Facebook和其他創建登錄帳戶。Web令牌認證 - 無MediaTypeFormatter
我遇到的問題是嘗試讀取登錄期間從API返回的錯誤,如錯誤密碼。我看到很多很多關於類似錯誤的帖子「沒有MediaTypeFormatter可用於從媒體類型爲'text/html'的內容中讀取類型爲的東西。」但無法解決此問題。
的API只需要返回JSON所以在我WebApiConfig.cs文件 GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
這是我在提琴手後
這裏是迴應:
and the Textview of the response whic^h看起來像JSON我
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
Yoda test = new Yoda() { email = model.Email, password = model.Password };
HttpClient client = CreateClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
//client.DefaultRequestHeaders.TryAddWithoutValidation("content-type", "application/x-www-form-urlencoded");
client.DefaultRequestHeaders.TryAddWithoutValidation("content-type", "application/json");
HttpResponseMessage result = await client.PostAsJsonAsync(_apiHostURL, test);
result.EnsureSuccessStatusCode();
if (result.IsSuccessStatusCode)
{
var token = result.Content.ReadAsAsync<TokenError>(new[] { new JsonMediaTypeFormatter() }).Result;
}
public class TokenError
{
[JsonProperty("access_token")]
public string AccessToken { get; set; }
[JsonProperty("token_type")]
public string TokenType { get; set; }
[JsonProperty("expires_in")]
public int ExpiresIn { get; set; }
[JsonProperty("refresh_token")]
public string RefreshToken { get; set; }
[JsonProperty("error")]
public string Error { get; set; }
}
public class Yoda
{
public string email { get; set; }
public string password { get; set; }
public string grant_type
{
get
{
return "password";
}
}
}
確切的錯誤是 「沒有MediaTypeFormatter可從與媒體類型‘text/html的’內容閱讀類型的對象‘TokenError’。 「