ASP NET Web Api : Windows Authentication example

Scenario : 

I have created my web api and hosted it on IIS enabling Windows Authentication on IIS and in api configuration files .

Target:  Another client app should be able to call my api via windows authentication

Web Api code :

 

public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { “value1”, “value2” };
}

 

 

Client :

 

string baseAddress = “http://localhost:88/&#8221;;
WebRequestHandler handler = new WebRequestHandler()
{
AllowAutoRedirect = false,
UseProxy = false,
Credentials = System.Net.CredentialCache.DefaultNetworkCredentials
};

HttpClient client = new HttpClient(handler);
client.BaseAddress = new Uri(baseAddress);

// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(“application/json”));
// List all items.
HttpResponseMessage response = client.GetAsync(“api/values”).Result;
if (response.IsSuccessStatusCode)
{
// Parse the response body
var products = response.Content.ReadAsAsync<IEnumerable<string>>().Result;
foreach (var p in products)
{
Response.Write(p.ToString());
}
}
else
{
Response.Write(“Error.”);
}

 

 

Advertisements

2 thoughts on “ASP NET Web Api : Windows Authentication example

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s