手把手教你在.NET中創(chuàng)建Web服務(wù)實現(xiàn)方法
最近發(fā)現(xiàn)在.NET平臺下使用Web服務(wù)還是很簡單的。
下面舉個在.NET平臺下創(chuàng)建Web服務(wù)的簡單例子。首先用Visul Studio .Net創(chuàng)建一個C# 項目Asp.Net Web服務(wù)程序,源代碼如下:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Web;
using System.Web.Services;
namespace author
{
/// <summary>
/// Service1 的摘要說明。
/// </summary>
public class Service1 : System.Web.Services.WebService
{
public Service1()
{
//CODEGEN: 該調(diào)用是 ASP.NET Web 服務(wù)設(shè)計器所必需的
InitializeComponent();
}
#region 組件設(shè)計器生成的代碼
//Web 服務(wù)設(shè)計器所必需的
private IContainer components = null;
/// <summary>
/// 設(shè)計器支持所需的方法 - 不要使用代碼編輯器修改
/// 此方法的內(nèi)容。
/// </summary>
private void InitializeComponent()
{
}
/// <summary>
/// 清理所有正在使用的資源。
/// </summary>
protected override void Dispose( bool disposing )
{
if(disposing && components != null)
{
components.Dispose();
}
base.Dispose(disposing);
}
#endregion
// WEB 服務(wù)示例
// HelloWorld() 示例服務(wù)返回字符串 Hello World
// 若要生成,請取消注釋下列行,然后保存并生成項目
// 若要測試此 Web 服務(wù),請按 F5 鍵
// [WebMethod]
// public string HelloWorld()
//{
// return "Hello World!";
//}
}
}
這些代碼都是系統(tǒng)自動生成的,從這里可以看到,普通的方法添加了WebMethod屬性后就成了Web方法了。下面給這段代碼添加一個訪問SQL Server數(shù)據(jù)庫的方法,代碼如下:
[WebMethod]
public DataSet DataVisit(string id)
{
string mySelectQuery = "Select au_id, au_fname, au_lname From authors where au_id != '"+id+"'";
string myConn = @"server=localhost; uid=sa; database=pubs";
SqlConnection myConnection = new SqlConnection(myConn);
SqlCommand myCmd = new SqlCommand(mySelectQuery, myConnection);
myConnection.Open();
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = myCmd;
DataSet myDs = new DataSet();
adapter.Fill(myDs, "author_name");
myConnection.Close();
return myDs;
}
這樣就創(chuàng)建了一個Web服務(wù)了,在Web應用程序里就可以通過添加“Web引用”來使用這個服務(wù)了。
相關(guān)文章
asp.net 中將表單提交到另一頁 Code-Behind(代碼和html在不同的頁面)
To send Server control values from a different Web Forms page2009-04-04
ASP.NET MVC 4使用PagedList.Mvc分頁的實現(xiàn)代碼
本篇文章主要介紹了ASP.NET MVC 4使用PagedList.Mvc分頁的實現(xiàn)代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-07-07
.Net?Core?Aop之IResourceFilter的具體使用
本文主要介紹了.Net?Core?Aop之IResourceFilter的具體使用,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-02-02
ASP.NET core Web中使用appsettings.json配置文件的方法
這篇文章主要給大家介紹了在ASP.NET core Web中使用appsettings.json配置文件的方法,文中給出了詳細的示例代碼,需要的朋友可以參考學習,下面來一起看看吧。2017-04-04
.Net筆記:System.IO之windows文件操作的深入分析
本篇文章是對.Net中windows文件操作的使用進行了詳細的分析介紹,需要的朋友參考下2013-05-05

