Nicolas Straub
Nicolas Straub

Reputation: 3411

calling a wcf webapi service with basic authentication from an asp.net 2.0 project

I'm working on a project that uses wcf webapi to expose all it's functionality as web services. I then consume these with various views (well two for now). One of these views is a legacy asp.net 2.0 project that will eventually be phased out once this new project has feature parity. I'm trying to consume these services by adding a service reference to the project but can't get it to work because the wcf api uses basic http auth and I can't configure that in the wizard. How do I manually add the service reference to my asp.net project?

Thanks!

Upvotes: 1

Views: 1764

Answers (1)

Alexander Zeitler
Alexander Zeitler

Reputation: 13109

When working with WCF Web API, you don't use service references but the new HttpClient instead e.g.:

var client = new HttpClient();
var byteArray = Encoding.ASCII.GetBytes(userName + ":" + password);
client.DefaultRequestHeaders.Authorization = 
    new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
var task = client.GetAsync("http://webapi/contact/1");
var contact = task.ContinueWith(
    t => {
        return t.Result.Content.ReadAsAsync<Contact>();
}).Unwrap().Result;

If you need to use .NET 2.0, you can use the HttpWebRequest (the HttpClient sample relies on .NET 4.0 as it is part of WCF Web API):

Uri myUri = new Uri("http://webapi/contact/1");
WebRequest myWebRequest = HttpWebRequest.Create(myUri);

HttpWebRequest myHttpWebRequest = (HttpWebRequest)myWebRequest;

NetworkCredential myNetworkCredential = 
    new NetworkCredential(username, password);

CredentialCache myCredentialCache = new CredentialCache();
myCredentialCache.Add(myUri, "Basic", myNetworkCredential);

myHttpWebRequest.PreAuthenticate = true;
myHttpWebRequest.Credentials = myCredentialCache;

WebResponse myWebResponse = myWebRequest.GetResponse();

Stream responseStream = myWebResponse.GetResponseStream();

Upvotes: 2

Related Questions