2 Web服务中的异常处理

Web服务的实现
为了达到这个示例的目的,我们创建一个名为CategoriesService的Web服务,选择一个可视化的C#ASP.NETWeb服务作为项目的模版 。一旦创建项目,我们就添加一个名为AddCategories的方法,并且给这个方法添加下列代码:
[WebMethod]
publicboolAddCategories(stringxml)
{
try
{
using(SqlConnectionconn=newSqlConnection())
{
if(ValidateXml(xml))
{
XmlDocumentdoc=newXmlDocument();
doc.LoadXml(xml);
conn.ConnectionString=
"server=localhost;uid=sa;pwd=thiru;database=northwind";
conn.Open();
XmlNamespaceManagernsManager=new
XmlNamespaceManager(doc.NameTable);
//AddthenamespacetotheNamespaceManager
nsManager.AddNamespace("catNS",
"http://tempuri.org/CategoriesNamespace");
XmlNodecategoryNode=
doc.DocumentElement.SelectSingleNode("catNS:Category",
nsManager);
stringcategoryName=
categoryNode.SelectSingleNode("catNS:CategoryName",
nsManager).InnerText;
stringcategoryDescription=
categoryNode.SelectSingleNode("catNS:CategoryDescription",
nsManager).InnerText;
SqlCommandcommand=new
SqlCommand("usp_InsertCategories",conn);
command.CommandType=CommandType.StoredProcedure;
【2 Web服务中的异常处理】//AddtheCategoryNameparameter
SqlParameterparamCategoryName=new
SqlParameter("@CategoryName",SqlDbType.NVarChar,15);
paramCategoryName.Direction=ParameterDirection.Input;
paramCategoryName.Value=https://www.rkxy.com.cn/dnjc/categoryName;
command.Parameters.Add(paramCategoryName);
//AddtheDescriptionparameter
SqlParameterparamDescription=new
SqlParameter("@Description",SqlDbType.Text);
paramDescription.Direction=ParameterDirection.Input;
paramDescription.Value=https://www.rkxy.com.cn/dnjc/categoryDescription;
command.Parameters.Add(paramDescription);
command.ExecuteNonQuery();
}
else
throw
RaiseException("AddCategories",
"http://tempuri.org/CategoriesService",
builder.ToString(),
"2000","AddCategories",FaultCode.Client);
}
returntrue;
}
catch(SoapExceptionsoapEx)
{
throwsoapEx;
}
catch(Exceptionex)
{
EventLog.WriteEntry("Test",ex.Message);
throw
RaiseException("AddCategories",
"http://tempuri.org/CategoriesService",ex.Message,
"1000",ex.Source,FaultCode.Server);
}
}

正如其名所提示的那样,AddCategories方法负责把category的详细信息添加到Northwind数据库的categories表中 。在执行添加操作之前,AddCategories方法使用一个外部的XML模式文件校验被添加的XML数据,如果校验失败,它给Web服务的客户端抛出一个异常 。
让我们来大致浏览上面的代码吧 。首先,把XML数据传递给它,调用ValidateXml方法 。过一会我们再来看ValidateXml方法的代码 。ValidateXml方法返回true或false,这完全取决于XML校验是否成功 。如果返回true,那么就创建一个XmlDocument对象实例,并给它导入XML数据,另外还设置ConnectionString属性来初始化SqlConnection对象,然后调用SqlConnection对象的Open方法 。其次,创建一个XmlNamespaceManager实例,调用AddNamespace方法关联一个命名空间 。一旦关联命名空间,我们就可以使用命名空间标识符引用正确的XML元素 。再次,创建一个SqlParameter对象实例,给存储过程添加参数 。最后,调用SqlCommand对象的ExecuteNonQuery方法执行存储过程 。
如果ValidateXml方法返回false,则用名为RaiseException的助手方法抛出SoapException 。我们现在就来讨论RaiseException 。RaiseException方法一个基本的助手方法,它封装用来从Web服务中抛出异常的代码 。RaiseException方法的最后一个参数是一个枚举常量,它的定义如下 。

推荐阅读