0

使用 Visual Studio 2013,我创建了一个新的 Web API 2 项目和一个新的 MVC 项目。将有其他客户端访问 API,这就是创建它的原因。最终,API 的客户端将允许用户使用 Facebook 和其他方式创建登录帐户。

我在尝试读取登录期间从 API 返回的错误时遇到的问题,例如密码错误。我看过很多很多关于类似错误的帖子,例如“没有 MediaTypeFormatter 可用于从媒体类型为‘text/html’的内容中读取类型对象。但无法解决此问题。

API 只需要返回 json 所以在我的 WebApiConfig.cs 文件中是 GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

这是我在提琴手的帖子

在此处输入图像描述

这是响应:

在此处输入图像描述

以及对我来说看起来像 json 的响应的 Textview 在此处输入图像描述

[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’类型的对象。”

4

1 回答 1

0

经过大量搜索后,我的代码似乎没有太大问题,只是 Web Api 中的 Token 端点不接受 json。我正在玩控制台应用程序。

    using Newtonsoft.Json;
    using System.Net.Http.Formatting; //Add reference to project.

    static void Main(string[] args)
    {
        string email = "test@outlook.com";
        string password = "Password@123x";

        HttpResponseMessage lresult = Login(email, password);

        if (lresult.IsSuccessStatusCode)
        {
        // Get token info and bind into Token object.           
            var t = lresult.Content.ReadAsAsync<Token>(new[] { new JsonMediaTypeFormatter() }).Result;
        }
        else
        {
            // Get error info and bind into TokenError object.
            // Doesn't have to be a separate class but shown for simplicity.
            var t = lresult.Content.ReadAsAsync<TokenError>(new[] { new JsonMediaTypeFormatter() }).Result;                
        }
    }

    // Posts as FormUrlEncoded
    public static HttpResponseMessage Login(string email, string password)
    {
        var tokenModel = new Dictionary<string, string>{
            {"grant_type", "password"},
            {"username", email},
            {"password", password},
            };

        using (var client = new HttpClient())
        {
            // IMPORTANT: Do not post as PostAsJsonAsync.
            var response = client.PostAsync("http://localhost:53007/token",
                new FormUrlEncodedContent(tokenModel)).Result;

            return response;
        }
    }

      public class Token
    {
        [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("userName")]
        public string Username { get; set; }

        [JsonProperty(".issued")]
        public DateTime Issued { get; set; }

        [JsonProperty(".expires")]
        public DateTime Expires { get; set; }
    }

    public class TokenError
    {            
        [JsonProperty("error_description")]
        public string Message { get; set; }
        [JsonProperty("error")]
        public string Error { get; set; }
    }
于 2016-03-11T23:19:18.353 回答