0
我是Web服務和.NET的新手。 我必須驗證正在使用http post訪問的Web服務。驗證Web服務選項
我試着把一個自定義的肥皂標題,並將其發送到服務,並檢查服務中的標題,但標題對象始終爲空的服務。
此外,如果我把用戶名和密碼選項放在http標題中,我如何在服務器上驗證它們?
在此先感謝
客戶端代碼:
private void button1_Click(object sender, EventArgs e)
{
HttpWebRequest request;
string strSOAPRequestBody = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"+
"<soap:Header>"+
"<AuthHeader xmlns=\"http://tempuri.org/\">" +
"<Username>apple</Username>"+
"<Password>apple</Password>"+
"</AuthHeader>"+
"</soap:Header>"+
"<soap:Body xmlns=\"http://tempuri.org/\">"+
"<HelloWorld>"+
"</soap:Body>"+
"</soap:Envelope>";
request = (HttpWebRequest)WebRequest.Create("http://localhost:1494/Service1.asmx/HelloWorld");
request.Accept = "text/xml";
request.Method = "POST";
request.ContentType = "application/soap+xml; charset=utf-8";
request.ContentLength = strSOAPRequestBody.Length;
using (Stream stream = request.GetRequestStream())
{
using (StreamWriter sw = new StreamWriter(stream))
{
sw.Write(strSOAPRequestBody);
sw.Flush();
}
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader responseStream = new StreamReader(response.GetResponseStream()))
{
txtResponse.Text = System.Web.HttpUtility.HtmlDecode(responseStream.ReadToEnd());
}
}
}
服務
public class Service1 : System.Web.Services.WebService
{
public AuthHeader Authentication;
[WebMethod]
[SoapHeader("Authentication", Direction = SoapHeaderDirection.In)]
public XmlDocument HelloWorld()
{
XmlDocument response = new XmlDocument();
try
{
//Boolean validateUser = Membership.ValidateUser(Authentication.Username, Authentication.Password);
if (Authentication != null)
{
response.LoadXml(String.Format("{0}{1}{2}", "<BOM>", "Hurray", "</BOM>"));
}
}
catch(Exception ex)
{
response.LoadXml(String.Format("{0}{1}{2}", "<Error>", ex.Message, "</Error>"));
}
return response;
}
}
另外,避免使用字符串創建XML。如果用戶的密碼中包含以下任何字符,它會變得繁榮:<, >,&(以及更多)。請參閱http://dotnetslackers.com/articles/aspnet/Securing-ASP-Net-Web-Services-with-Forms-Authentication.aspx中的文章,以獲得更好的(且非常相似,因此更改應該很少)的實現使用Forms Authentication來保護Web服務的安全。 – 2010-09-16 07:15:04
@Andreas Paulsson,好文章。我同意。手工製作XML並不是製作實施的方式 - 至少使用XML框架類。 – 2010-09-16 07:45:39
謝謝大家,我會避免使用字符串中的XML。謝謝Tuzo。 – Dheeraj 2010-09-16 12:46:36