简体   繁体   中英

C# Windows Universal Application consuming WebAPI gives Unauthorized response

I am trying to consume a Web API in windows universal application on Windows 10 using Visual Studio 15...

I am using following code to get the employee list from WebAPI.

HttpClient client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });

client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.BaseAddress = new Uri("http://localhost:59591/");
HttpResponseMessage response = client.GetAsync("api/Employee/GetAllEmployee").Result;

if (response.IsSuccessStatusCode)
{
    var employeelist = response.Content.ReadAsStringAsync();

}

But in response I am getting

Status Code: 401, ReasonPhrase: 'Unauthorized'.

The same code works fine if I create a Windows Forms Application.

Is there anything specific I need to do in order to use Web API in Windows Universal Application?

You cannot reach the localhost from a UWP application. The security model does not allow this.

You can get some details about how isolation is working here :

Network isolation and loopback

IP loopback addresses and the loopback interface have traditionally been used for communication between different applications over the network, as well as for interprocess communication within several applications on a local computer.

Network communications using an IP loopback address cannot be used for interprocess communication (between two different apps) because this is restricted by network isolation. Network communication using an IP loopback address is allowed within an app within the same process for communication purposes.

For more information on enabling developer access to IP loopback addresses between apps for debugging purposes, see How to enable loopback and debug network isolation.

For debugging purpose, you can turn it off. You can find some documentation here

A developer can also use the CheckNetIsolation.exe tool to manually add loopback exemptions for an app.

To exempt an app from loopback restrictions, the app ID for the package must be provided. The example command below exempts an app from loopback restrictions.

CheckNetIsolation.exe LoopbackExempt –a –p=S-1-15-2-4125766819-3228448775-2449327860-2490758337-1264241865-3581724871-2122349299

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM