简体   繁体   English

WebClient在GET请求MVC 5上返回错误500

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

I'm having an issue with the WebClient. WebClient出现问题。 I'm using API-key authentication, and the API-key is indeed legit. 我正在使用API​​密钥身份验证,并且API密钥确实是合法的。 If I turn off authentication on my API it gets the data without any issues, however, if I enable checking for "Authentication" in the WebClient header, it returns a 401 with a wrong/invalid API-key, but with a valid one it returns error 500. 如果我关闭我的API的身份验证,它会毫无问题地获取数据,但是,如果我启用了WebClient标头中的“身份验证”检查功能,它将返回带有错误/无效的API密钥的401,但带有一个有效的API密钥返回错误500。

Code with the WebClient: 使用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: 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");
    }
}

Thanks in advance! 提前致谢!

不知道这是否是相同的问题,但是我收到500并通过设置接受语言标头(使用UserAgent)进行了修复:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM