最近做一个web服务接收手机端的考勤签到操作,利用手机签到,发送相关时间、地理位置等信息到服务器进行验证。
我这里直接写在一个WebForm页面后台,没有创建Web服务,比较简单。
首先我们用的是post请求方式,所以直接在后台代码中利用string Name = Request.Form["Name"].ToString().Trim();的方式获取手机端传送来的数据,注意判断是否为空。
利用获取的信息,例如:用户编号、密码。连接数据库执行Sql语句,判断是否存在对应用户以及密码是否正确,然后判断手机唯一标示的IMSI信息是否为用户的绑定手机信息,若是,则登录成功并返回登陆成功的信息。否则,向手机端发送错误消息。
贴代码如下:
SqlDataAdapter da;
DataSet ds;
SqlCommand sc;
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(SqlConnect.DocumentManagerConnectionString); //建立数据库连接
string userId = Request.Form["User_Id"].ToString().Trim(); //获取用户编号
string password = Request.Form["Password"].ToString().Trim(); //获取密码
string imsi = Request.Form["IMSI"].ToString().Trim(); //获取手机端唯一的IMSI
try
{
string s = "SELECT * FROM UserTbl WHERE User_Id='" + userId + "'"; //查询对应编号的用户
da = new SqlDataAdapter(s, conn);
ds = new DataSet();
da.Fill(ds, "UserTbl");
if (ds.Tables["UserTbl"].Rows.Count == 0) //判断用户是否存在
{
Response.Write("User not exist");
}
else
{
if (password == ds.Tables["UserTbl"].Rows[0]["Password"].ToString()) //判断密码是否正确
{
if (imsi == ds.Tables["UserTbl"].Rows[0]["IMSI"].ToString()) //判断手机是否是用户绑定的手机
{
StringBuilder sb = new StringBuilder("YES;"); //成功登录
string name=ds.Tables["UserTbl"].Rows[0]["User_Name"].ToString();
sb.Append(name);
Response.Write(sb);
}
else
{
Response.Write("IMSI error"); //手机不是用户绑定的手机
}
}
else
{
Response.Write("Password error"); //密码错误
}
}
}
catch (SqlException ex)
{
throw ex;
}
}
以上操作登录成功之后,手机端可以进行签到验证,web服务应该响应该操作哦,向数据库插入数据。
贴代码如下:
SqlConnection conn;
SqlCommand sc;
string userId = Request.Form["User_Id"].ToString().Trim(); //用户编号
string userName = Request.Form["User_Name"].ToString().Trim(); //用户姓名
string attendType = Request.Form["Attend_Type"].ToString().Trim(); //签到类型
string location = Request.Form["Location"].ToString().Trim(); //地理位置
string attendDate = Request.Form["Attend_Date"].ToString().Trim(); //签到时间
string jingLocation = Request.Form["Jing_Location"].ToString().Trim(); //经度
string weiLocation = Request.Form["Wei_Location"].ToString().Trim(); //纬度
string radius = Request.Form["Radius"].ToString().Trim(); //精确度
try
{
conn = new SqlConnection(SqlConnect.DocumentManagerConnectionString);
string insertSql = "INSERT INTO AttendTbl(User_Id,User_Name,Attend_Type,Location,Attend_Date,Jing_Location,Wei_Location,Radius)VALUES('" + userId + "','" + userName + "','" + attendType + "','" + location + "','" + attendDate + "','" + jingLocation + "','" + weiLocation + "','" + radius + "')";
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
sc = new SqlCommand(insertSql, conn);
int x = sc.ExecuteNonQuery();
if (x > 0)
{
Response.Write("Success");
}
}
catch (SqlException ex)
{
throw ex;
}
finally
{
conn.Close();
}
这样签到信息就成功录入。所以Web服务接收手机端数据的核心代码就是string Name = Request.Form["Name"].ToString().Trim();(采用post方式的情况下)