Reputation: 1865
I'm having an issue with the WebClient. I'm using API-key authentication, and the API-key is indeed legit. 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.
Code with the 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");
}
}
Thanks in advance!
Upvotes: 0
Views: 944
Reputation: 571
Not sure if it's the same problem but I was receiving a 500 and I fixed by setting the accept language header (with UserAgent):
client.Headers.Add(HttpRequestHeader.AcceptLanguage, "en");
Upvotes: 1