使用ASP.NET Web API构建一个简单的应用。
示例:使用ASP.NET Web API提供获取用户列表和用户信息接口。
1、在Models目录下创建用户信息类(UserModel.cs)
/// <summary>
/// 用户信息类
/// </summary>
public class UserModel
{
/// <summary>
/// 用户ID
/// </summary>
public int ID { get; set; }
/// <summary>
/// 用户名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 性别
/// </summary>
public string Sex { get; set; }
}
2、在Models目录下创建用户参数类(UserParam.cs)
/// <summary>
/// 用户参数类
/// </summary>
public class UserParam
{
/// <summary>
/// 用户ID
/// </summary>
public int ID { get; set; }
/// <summary>
/// 用户名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 性别
/// </summary>
public string Sex { get; set; }
}
3、创建API执行状态编码枚举(ApiStatusCode.cs)
/// <summary>
/// API执行状态编码枚举
/// </summary>
public enum ApiStatusCode
{
/// <summary>
/// 参数缺失或无效
/// </summary>
ParamInvalid = 1000,
/// <summary>
/// 操作成功
/// </summary>
Success = 2000,
/// <summary>
/// 系统异常
/// </summary>
SystemException = 5000,
/// <summary>
/// 操作失败
/// </summary>
Failed = 5500
}
4、在Models目录下创建Api返回结果类(ApiResultModel.cs)
/// <summary>
/// Api返回结果类
/// </summary>
public class ApiResultModel
{
/// <summary>
/// 状态码
/// </summary>
public ApiStatusCode StatusCode { get; set; }
/// <summary>
/// 返回消息描述
/// </summary>
public string Message { get; set; }
/// <summary>
/// 返回数据
/// </summary>
public object Data { get; set; }
}
5、在Controllers目录下创建WebApi控制器基类(BaseApiController.cs),并编写相关WebApi的公共处理方法。
/// <summary>
/// WebApi控制器基类
/// </summary>
public class BaseApiController : ApiController
{
/// <summary>
/// 获取当前请求的Token值
/// </summary>
public static string GetRequestToken()
{
string token = HttpContext.Current.Request.Headers["Access-Token"];
return token;
}
/// <summary>
/// 生成新Token
/// </summary>
/// <returns></returns>
public static string CreateNewToken()
{
//TODO:生成新Token方法待完成
string token = "12345";
return token;
}
/// <summary>
/// 获取POST请求Request中的参数
/// </summary>
public static string GetRequestParam()
{
using (StreamReader sr = new StreamReader(HttpContext.Current.Request.InputStream))
{
string reqParam = sr.ReadToEnd();
return reqParam;
}
}
/// <summary>
/// 获取POST请求Request中的参数并反序列化为T对象
/// </summary>
public static T GetRequestParam<T>() where T : class,new()
{
using (StreamReader sr = new StreamReader(HttpContext.Current.Request.InputStream))
{
string reqParam = sr.ReadToEnd();
if (string.IsNullOrWhiteSpace(reqParam))
{
return default(T);
}
return JsonConvert.DeserializeObject<T>(reqParam);
}
}
/// <summary>
/// 将对象转换为Json格式的HttpResponseMessage对象
/// </summary>
public static HttpResponseMessage ToResponseJson(ApiResultModel model)
{
string str = JsonConvert.SerializeObject(model);
var result = new HttpResponseMessage
{
Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json")
};
//生成新Token
string token = CreateNewToken();
//添加响应头信息
result.Headers.Add("Access-Control-Expose-Headers", "Access-Token");
result.Headers.Add("Access-Token", token);
return result;
}
}
6、在Controllers目录下创建用户控制器(UserController.cs),该控制器继承BaseApiController基类,并编写相关接口方法。
/// <summary>
/// 用户控制器
/// </summary>
public class UserController : BaseApiController
{
/// <summary>
/// 查询用户列表
/// </summary>
[HttpPost]
public HttpResponseMessage QueryUserList()
{
ApiResultModel result = new ApiResultModel();
//获取查询参数
UserParam param = GetRequestParam<UserParam>();
if (param == null)
{
result.StatusCode = ApiStatusCode.ParamInvalid;
result.Message = "参数缺失或无效";
result.Data = null;
return ToResponseJson(result);
}
//获取用户数据列表
List<UserModel> userList = GetUserData();
//根据查询参数,筛选数据
if (!String.IsNullOrEmpty(param.Name))
{
userList = userList.Where(a => a.Name == param.Name).ToList();
}
if (!String.IsNullOrEmpty(param.Sex))
{
userList = userList.Where(a => a.Sex == param.Sex).ToList();
}
//返回最终结果
result.StatusCode = ApiStatusCode.Success;
result.Message = "操作成功";
result.Data = userList;
return ToResponseJson(result);
}
/// <summary>
/// 查询单个用户
/// </summary>
[HttpPost]
public HttpResponseMessage QueryUserInfo()
{
ApiResultModel result = new ApiResultModel();
//获取查询参数
UserParam param = GetRequestParam<UserParam>();
if (param == null)
{
result.StatusCode = ApiStatusCode.ParamInvalid;
result.Message = "参数缺失或无效";
result.Data = null;
return ToResponseJson(result);
}
if (param.ID <= 0)
{
result.StatusCode = ApiStatusCode.ParamInvalid;
result.Message = "无效的ID值参数";
result.Data = null;
return ToResponseJson(result);
}
//获取用户数据列表
List<UserModel> userList = GetUserData();
//根据查询参数,筛选数据
UserModel user = userList.FirstOrDefault(a => a.ID == param.ID);
//返回最终结果
result.StatusCode = ApiStatusCode.Success;
result.Message = "操作成功";
result.Data = user;
return ToResponseJson(result);
}
/// <summary>
/// 获取用户数据列表
/// </summary>
private List<UserModel> GetUserData()
{
List<UserModel> result = new List<UserModel>();
result.Add(new UserModel() { ID = 1, Name = "张三", Sex = "男" });
result.Add(new UserModel() { ID = 2, Name = "李四", Sex = "女" });
result.Add(new UserModel() { ID = 3, Name = "王五", Sex = "男" });
result.Add(new UserModel() { ID = 4, Name = "孙六", Sex = "女" });
return result;
}
}
7、运行测试
这里测试第一个接口方法(查询用户列表),使用测试工具:Postman,如下图。
请求参数:
{
"Name": "",
"Sex": "男"
}
响应结果:
{
"StatusCode": 2000,
"Message": "操作成功",
"Data": [{
"ID": 1,
"Name": "张三",
"Sex": "男"
},
{
"ID": 3,
"Name": "王五",
"Sex": "男"
}
]
}