Nancy 简单学习

1. 环境 vs2010 , nancy 

2. 需要测试的功能

   1. 输出

     页面输出简单文本

   2. 输出json 数据

3. 操作

    1. 创建asp.net 空项目

    2. 添加引用Nancy库 使用nuget

    如图:

   

  4. 编码

     创建模块: UserLoginModel

     

public class UserLoginModel:NancyModule
{

public UserLoginModel()
{
Get["/login"] = _=> "dalong";   //  输出dalong
Get["/App"] = parameter =>
{
var usermodel = new UserModel { Age = 555, Name = "dalong" };   // 返回(按照客户请求的模式)
return Negotiate.WithStatusCode(HttpStatusCode.OK)
.WithModel(usermodel);
};
Get["/App/{id}"] = parameter =>     // 根据获取的参数创建集合,并返回数据(按照客户请求的模式)
{
// var usermodel = new UserModel { Age = 555, Name = "dalong" };
var id = parameter.id;
List<UserModel> list = CreateUserList.CreateList(id);
return Negotiate.WithStatusCode(HttpStatusCode.OK).WithModel(list);
};

}
}

         UserModel :

public class UserModel
{

public int Age { get; set; }

public string Name { get; set; }
}

          CreateUserList:

public class CreateUserList
{

public static List<UserModel> CreateList(int Startindex)
{
List<UserModel> list = new List<UserModel>();

for (int i = Startindex; i < Startindex+10; i++)
{

list.Add(new UserModel { Name = "dalong" + i, Age = i });
}
return list;

}
}

5. 测试效果:

     json 格式的测试使用dev http client 

     截图如下:

     

原文地址:https://www.cnblogs.com/rongfengliang/p/4182279.html