1.服务主体文件代码
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
namespace SrvTest
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。
//这里要取消注释
[System.Web.Script.Services.ScriptService]
public class srv : System.Web.Services.WebService
{
[WebMethod]
//指定请求是application/json格式
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public void HelloWorld(string str)
{
string usercode = str;
DBHelper db = new DBHelper();//DBHelper是数据库连接类,自行实现
string res = "";
using (DataTable tb = db.GetTable("select UserName from t_user where UserCode = '"+usercode+"'"))
{
if (tb == null || tb.Rows.Count <= 0)
{
res = "未查询到数据";
}
else
{
res = tb.Rows[0]["UserName"].ToString();
}
}
db.Dispose();
Context.Response.Clear();
//指定返回结果也是application/json
Context.Response.ContentType = "application/json";
//自己拼凑个json格式字符串
string s = "{\"返回结果 \":\""+res+"\"}";
Context.Response.Write(s);
//加上下面两句是防止接收到的返回字符串后面有{"d":null}
Context.Response.Flush();
Context.Response.End();
}
public void HelloWorldNoParam()
{
Stream s = HttpContext.Current.Request.InputStream;//从输入流获得json字符流
//还原数据流
byte[] b = new byte[s.Length];
s.Position = 0;
s.Read(b, 0, (int)s.Length);
string jsontext = Encoding.UTF8.GetString(b); //JSON字符串
DBHelper db = new DBHelper();
db.ExcuteSQL("insert into callBackTb (str) values('"+ jsontext + "')");
db.Dispose();
Context.Response.Clear();
Context.Response.ContentType = "application/json";
string rs = "{\"status \":1,\"msg\":\"操作成功\"}";
Context.Response.Write(rs);
Context.Response.Flush();
//Context.Response.End();
Context.Response.SuppressContent = true;
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
}
}
2.web.config文件,主要放的是数据库连接参数和查询超时时间
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<customErrors mode="Off"/>
<webServices>
<protocols>
<add name= "HttpPost"/>
<add name= "HttpGet"/>
</protocols>
</webServices>
</system.web>
<connectionStrings>
<add name="conn" connectionString="server=127.0.0.1;Initial Catalog=demo;uid=sa;pwd=;Pooling=True;Min Pool Size=10;Max Pool Size=20000;timeout=60"/>
</connectionStrings>
<appSettings>
<add key="qryTime" value="30"/>
<add key="execTime" value="30"/>
</appSettings>
</configuration>
发布并部署在IIS上之后,进行测试,因为HelloWorld定义的参数名是 str,所以post参数中json的键名也叫 str