簡體   English   中英

WebClient在GET請求MVC 5上返回錯誤500

[英]WebClient returning error 500 on GET request MVC 5

WebClient出現問題。 我正在使用API​​密鑰身份驗證,並且API密鑰確實是合法的。 如果我關閉我的API的身份驗證,它會毫無問題地獲取數據,但是,如果我啟用了WebClient標頭中的“身份驗證”檢查功能,它將返回帶有錯誤/無效的API密鑰的401,但帶有一個有效的API密鑰返回錯誤500。

使用WebClient進行編碼:

public ActionResult Index()
{
    using (var client = new WebClient())
    {
        client.Headers.Clear();
        client.Headers.Add("Authorization", AppSettings.ApiKey());
        client.Headers.Add("Host", "localhost");
        client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
        var newsJson = client.DownloadString("http://localhost:59308/Api/ListNews");
        var newsJsonDeserialized = JsonConvert.DeserializeObject<List<News>>(newsJson);
        ViewData["NewsFeed"] = newsJsonDeserialized.ToList();
    }
    var dayMessages = new List<string> { "an astonishing", "an amazing", "a beautiful", "a gorgeous", "a loving" };
    var randomNumber = new Random().Next(dayMessages.Count);
    ViewData["DayOfWeekMsg"] = dayMessages[randomNumber] + " " + DateTime.Now.ToString("dddd");
    return View();
}

ApiController:

public ActionResult ListNews()
{
    using (var db = new Entities())
    {
        var apiToken = Request.Headers["Authorization"];
        var apiTokens = db.ApiTokens.ToList();
        var websiteUrl = Request.Url.Host;
        if (apiTokens.SingleOrDefault(i => i.Token == apiToken && i.WebsiteUrl == websiteUrl) == null)
        {
            return new HttpUnauthorizedResult();
        }
        var news = db.News;
        var newsList = news.ToList();
        return Content(JsonConvert.SerializeObject(newsList, Formatting.Indented), "application/json");
    }
}

提前致謝!

不知道這是否是相同的問題,但是我收到500並通過設置接受語言標頭(使用UserAgent)進行了修復:

client.Headers.Add(HttpRequestHeader.AcceptLanguage, "en");

暫無
暫無

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

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