我正在尝试使用受站点保护的WCF webserice。问题是,当我尝试浏览浏览器中的Web服务URL时,它与我提供的凭据一起工作正常。
但是当我尝试以编程方式执行相同操作时,它会抛出错误 - 错误#401未经授权。
供参考 - http://www.codeproject.com/Articles/80314/How-to-Connect-to-a-SiteMinder-Protected-Resource
CookieContainer cookies = null;
HttpWebRequest request = null;
HttpWebResponse response = null;
string responseString = null;
NameValueCollection tags = null;
string url = null;
url = PROTECTED_URL;
Debug.WriteLine("Step 1: Requesting page @" + url);
request = (HttpWebRequest)WebRequest.Create(url);
request.AllowAutoRedirect = false;
response = (HttpWebResponse)request.GetResponse();
ShowResponse(response);
// Step 2: Get the redirection location
// make sure we have a valid response
if (response.StatusCode != HttpStatusCode.Found)
{
throw new ApplicationException();
}
url = response.Headers["Location"];
// Step 3: Open a connection to the redirect and load the login form,
// from this screen we will capture the required form fields.
Debug.WriteLine("Step 3: Requesting page @" + url);
request = (HttpWebRequest)WebRequest.Create(url);
request.AllowAutoRedirect = false;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (Exception ex)
{
string str = ex.Message.ToString();
}
答案 0 :(得分:0)
我的HtTpClient
致电WCF
。
public async Task<string> webClient(string method, string uri)
{
try
{
var client = new HttpClient();
client.Timeout =new TimeSpan(0,0,0,10);
client.BaseAddress = new Uri(uri);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync(method).Result;
string content = await response.Content.ReadAsStringAsync();
return content;
}
catch (Exception ex)
{
return "Error";
}
}
Uri是基地址,方法是你的方法名称。
string response = webClient(uri + "/GetSomething/", uri).Result;