我已经使用 ASP.NET Web Api 构建了一个 ASP.NET MVC 4 网站,该网站将通过 IIS 中的 Windows 身份验证进行保护。在 Visual Studio 中一切正常;HttpClient 的调用正在工作,并且总是返回数据以及状态码 200。但是,当我发布到 IIS 时,这就是问题所在;当尝试调用 api 时,我总是得到一个 401 Unauthorized 与这些设置:
身份验证:仅 Windows 身份验证 授权:仅允许一个用户 - 我。
但是,当我将 Authorization 更改为 Allow All 时,它可以正常工作,但这不是我想要的行为。
我尝试直接从浏览器调用 API,仅将授权设置为我的帐户……它像一个好的小 Api 一样工作正常;除非我以其他用户身份登录,否则不会出现未经授权的错误。
所以我想这让我得出结论,网站与 API 的通信方式有问题。这是我的代码:
public ActionResult Index()
{
HttpClientHandler handler = new HttpClientHandler();
handler.UseDefaultCredentials = true;
using (HttpClient client = new HttpClient(handler))
{
var clientResult = client.GetAsync(
string.Format(@"{0}{1}",ConfigurationManager.AppSettings["WebApiBaseUri"].ToString(), "products")
).Result;
clientResult.EnsureSuccessStatusCode();
//if (clientResult.StatusCode != HttpStatusCode.OK)
//{
// ViewBag.Error = clientResult.StatusCode;
// ViewBag.User = userName;
// ViewBag.Message = clientResult.Content.ReadAsStringAsync().Result;
// return View();
//}
var receivedData = clientResult.Content.ReadAsStringAsync().Result;
List<ProductModel> data = JsonConvert.DeserializeObject<List<ProductModel>>(receivedData);
return View(data);
}
}
这是API端的代码:
public IQueryable<Product> Get()
{
_context = new InventoryContext();
return _context.Products.AsQueryable();
}
有人知道我在做什么错吗?