c# - HttpWebRequest Authentication not working -
alright, i'm writing program access restful service, first must provide authentication website. have valid credentials , entire code looks this:
using system; using system.collections.generic; using system.linq; using system.text; using system.collections; using system.net; using system.io; namespace accessapi { class program { static void main(string[] args) { string uri = "http://domainname/"; httpwebrequest request = (httpwebrequest)webrequest.create(uri); string auth = createauthorization("http://domainname/", "my\\username", "password"); request.headers["authorization"] = "basic " + auth; httpwebresponse response = (httpwebresponse)request.getresponse(); streamreader reader = new streamreader(response.getresponsestream()); console.writeline(reader.readtoend()); } static string createauthorization(string realm, string username, string password) { string auth = ((realm != null) && (realm.length > 0) ? realm + @"\" : "") + username + ":" + password; auth = convert.tobase64string(encoding.default.getbytes(auth)); return auth; } } } i've come far using few of solutions posted on other forums. while seemed work out people, doesn't me. first off, know credentials accurate. i'm able enter them on web browser , behave should. also, made sure "\" in them (there 1 in username) represented "\\" in code. every time run this, though, keep on getting "the remote server returned error: (401) unauthorized." can me troubleshoot through this? thank time!
from above code, when "auth" string getting composed auth string this: "http://domainname/:my\username:password"
the auth string should have format: domainname\username:password (the domain name optional).
Comments
Post a Comment