我遇到了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");
}
}
提前致谢!
答案 0 :(得分:1)
不确定是否是同样的问题,但我收到500并通过设置接受语言标题(使用UserAgent)修复:
client.Headers.Add(HttpRequestHeader.AcceptLanguage, "en");