从本地MVC站点调用本地WebAPI

本文关键字:WebAPI 调用 MVC 站点 | 更新日期: 2023-09-27 18:16:00

我使用Windows Authentication在本地机器上创建了一个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应用程序,或通过提琴手,我得到一个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/assignes/get直接从我的浏览器

从本地MVC站点调用本地WebAPI

你可以试试:

        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);
  }

正如@Gabbar上面的链接所提示的,我需要使用NetworkCredential s。我实现如下,它工作:

public ActionResult Index()
{
    var assignees = new object();
    using (var handler = new HttpClientHandler()) 
    {
        handler.Credentials = new System.Net.NetworkCredential(@"DOMAIN'USERNAME", "PASSWORD");
        using (var 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);
        }
    }
    return View(assignees);
}