WebServices應用(二)

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 若要容許使用 ASP.NET AJAX 從腳本中調用此 Web 服務,請取消註釋如下行。 
[ScriptService]
public class Caculate : WebService
{
    [WebMethod(Description = "加法")]
    [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
    public void Add(int i, int j)
    {
        Context.Response.ContentType = "application/json";
        var sum = new { Sum = i + j };
        Context.Response.Write(sum);
    }
}

一、上面的description必不可少,下面的scriptmethod 中應該指的是js之類腳本調用的時候容許httpget方法獲取,而且顯示爲json格式;這裏須要有一點注意的,前臺調用的時候,咱們直接輸出到頁面就能夠了,js能夠獲取的到,若是是後臺程序獲取的話,web

咱們在編寫webservice的時候方法必定要是帶返回值的,有利於其餘程序進一步操做。上面的能夠看作是寫給js調用的webservice,下面看一個是寫給後臺程序調用的webservice,具體代碼以下,eg:json

public class Caculate : WebService
{
    [WebMethod(Description = "加法")]
    [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
    public int Add(int i, int j)
    {
        return i + j;
    }
}

而後咱們在後臺調用便可,代碼以下,eg:app

protected void Page_Load(object sender, EventArgs e)
{
    CaculateSoap cs=new CaculateSoapClient();
    Response.Write(cs.Add(1, 5));
}

咱們引用的webservice要是變更的話,記得右鍵更新服務引用,這個時候會在webconfig中或者app.config中生成幾行沒有用的代碼,刪掉便可。spa

有的時候須要在webservice的webconfig中添加以下代碼,eg:code

<webServices>
    <protocols>
        <add name= "HttpPost"/>
        <add name= "HttpGet"/>
    </protocols>
</webServices>
相關文章
相關標籤/搜索