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