使用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’。 “