【发布时间】:2011-05-04 11:14:39
【问题描述】:
我已经编写了一个测试应用程序来根据内部 RESTful 服务验证一些用户详细信息。
如果我直接通过浏览器发出请求,我会收到来自服务的响应,但如果我通过代码发出请求,则响应表明我需要代理服务器身份验证。
虽然我可以提供用户可配置的设置,以便可以传递代理参数,但感觉不对,我不确定我的代码是否不正确。
下面是失败的代码 sn-p,后面是带有代理详细信息的 sn-p。
/// <summary>
/// Validate the user details
/// </summary>
/// <returns>True if the user credentials are valid, else false</returns>
public bool ValidateUser()
{
bool valid = false;
try
{
// Create the XML to be passed as the request
XElement root = BuildRequestXML("LOGON");
// Add the action to the service address
Uri serviceReq = new Uri(m_ServiceAddress + "?obj=LOGON");
// Make the RESTful request to the service using a POST
using (HttpResponseMessage response = new HttpClient().Post(serviceReq, HttpContentExtensions.CreateDataContract(itrent)))
{
// Retrieve the response for processing
response.Content.LoadIntoBuffer();
string returned = response.Content.ReadAsString();
// TODO: parse the response string for the required data
}
}
catch (Exception ex)
{
Log.WriteLine(Category.Serious, "Unable to validate the User details", ex);
valid = false;
}
return valid;
}
现在对于有效但有问题的块......
/// <summary>
/// Validate the user details
/// </summary>
/// <returns>True if the user credentials are valid, else false</returns>
public bool ValidateUser()
{
bool valid = false;
try
{
// Create the XML to be passed as the request
XElement root = BuildRequestXML("LOGON");
// Add the action to the service address
Uri serviceReq = new Uri(m_ServiceAddress + "?obj=LOGON");
// Create the client for the request
using (HttpClient client = new HttpClient())
{
// Create a proxy to get around the network issues and assign it to the http client
WebProxy px = new WebProxy( <Proxy server address>, <Proxy Server Port> );
px.Credentials = new NetworkCredential( <User Name>, <Password>, <Domain> );
client.TransportSettings.Proxy = px;
// Mare the RESTful request
HttpResponseMessage response = client.Post(serviceReq, HttpContentExtensions.CreateDataContract(root));
// Retrieve the response for processing
response.Content.LoadIntoBuffer();
string returned = response.Content.ReadAsString();
// TODO: parse the response string for the required data
}
}
catch (Exception ex)
{
Log.WriteLine(Category.Serious, "Unable to validate the User details", ex);
valid = false;
}
return valid;
}
我们非常感谢所有建议。 干杯。
【问题讨论】:
标签: c# web-services authentication rest proxy