国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 網站 > 建站經驗 > 正文

Web服務中的異常處理(2)

2019-11-02 16:58:16
字體:
來源:轉載
供稿:網友

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;//AddtheCategoryNameparameter

SqlParameterparamCategoryName=new

SqlParameter("@CategoryName",SqlDbType.NVarChar,15);

paramCategoryName.Direction=ParameterDirection.Input;

paramCategoryName.Value=categoryName;

command.Parameters.Add(paramCategoryName);

//AddtheDescriptionparameter

SqlParameterparamDescription=new

SqlParameter("@Description",SqlDbType.Text);

paramDescription.Direction=ParameterDirection.Input;

paramDescription.Value=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方法執行存儲過程。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 太谷县| 巴彦淖尔市| 化州市| 新民市| 临漳县| 翁源县| 贺兰县| 太白县| 曲周县| 呼和浩特市| 红桥区| 德州市| 百色市| 潞西市| 宜良县| 年辖:市辖区| 珲春市| 洛南县| 张掖市| 钦州市| 乌拉特中旗| 新绛县| 湖南省| 桐城市| 眉山市| 青冈县| 新邵县| 宜良县| 枣阳市| 镇平县| 河南省| 淄博市| 岑巩县| 南汇区| 亳州市| 东光县| 本溪市| 阜城县| 乐安县| 五大连池市| 织金县|