从本地MVC站点调用本地Web API

时间:2014-07-31 14:51:25

标签: c# asp.net-web-api asp.net-mvc-5

我使用 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 /。

2 个答案:

答案 0 :(得分:3)

你可以尝试:

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

答案 1 :(得分:1)

正如上面提到的@ 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);
}