我已经使用 Windows 身份验证 在我的本地计算机上创建了一个 WebAPI 应用程序。
我还创建了一个 MVC 5 应用程序,我正在尝试使用以下代码连接到我的 WebAPI:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:52613/api/acmeco/");
var result = client.GetAsync("assignees/get").Result;
string resultContent = result.Content.ReadAsStringAsync().Result;
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
assignees = json_serializer.DeserializeObject(resultContent);
}
问题是:每次我尝试通过 MVC 5 应用程序或通过 Fiddler 进行连接时,我都会收到 401 Unauthorized 错误。
我已经尝试了多种解决方案来解决这个问题,包括但不限于以下几种:
http://support.microsoft.com/kb/896861/en-us
有谁知道如何从本地 MVC 5 应用调用本地 WebAPI?
编辑:我也试过像这样将 CORS(跨源脚本)添加到 WebAPI,但似乎对 401 错误没有影响:
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class AssigneesController : ApiController
{
public Assignees AssigneeRepo = new Assignees();
// GET api/values
public IEnumerable<Assignee> Get(string @namespace)
{
return AssigneeRepo.GetAssigneesForTenant(@namespace);
}
}
但是,我可以直接从浏览器访问 localhost:52613/api/acmeco/assignees/get。
请您参考如下方法:
你可以试试:
HttpClientHandler handler = new HttpClientHandler()
{
UseDefaultCredentials = true
};
using(HttpClient client = new HttpClient(handler))
{
client.BaseAddress = new Uri("http://localhost:52613/api/acmeco/");
var result = client.GetAsync("assignees/get").Result;
string resultContent = result.Content.ReadAsStringAsync().Result;
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
assignees = json_serializer.DeserializeObject(resultContent);
}
