簡體   English   中英

Web令牌認證-沒有可用的MediaTypeFormatter

[英]Web Token Authenication - No MediaTypeFormatter available

使用Visual Studio 2013,我創建了一個新的Web API 2項目和一個新的MVC項目。 將會有其他客戶端訪問該API,這就是創建該API的原因。 最終,API的客戶端將允許用戶使用Facebook等創建登錄帳戶。

我在嘗試讀取登錄期間從API返回的錯誤(例如錯誤密碼)時遇到的問題。 我已經看到了關於類似的錯誤很多,很多帖子“沒有MediaTypeFormatter可讀取的從媒體類型‘text / html的’內容類型的東西的對象。” 但無法解決此問題。

該API僅需要返回json,因此在我的WebApiConfig.cs文件中為GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

這是我在提琴手的帖子

在此處輸入圖片說明

這是回應:

在此處輸入圖片說明

和響應的Textview對我來說看起來像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'的對象。”

經過大量搜索之后,我的代碼似乎並沒有什么問題,只是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; }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM