WebAPI
WebAPI (Application Programming Interface)
相比WCF、WebService 更加轻量级,更加简单 ,传输效率更高
可以对接各种客户端(浏览器,移动设备)
WebAPI 中一定要做好异常处理
1.设置返回数据类型
打开文件 APP_Start=>WebApiConfig.cs ,添加如下代码
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear(); //不提供XML格式数据
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SupportedMediaTypes.Clear(); //不提供Json格式数据
2.示例
实体类:
public class Book
{
public string Id { get; set; }
public string Name { get; set; }
public string Price { get; set; }
public string Des { get; set; }
}
控制器:
public class BookController : ApiController
{
public static List<Book> listBooks = new List<Book> {
new Book() { Id="1", Name ="C# 入门经典",Price="66",Des="好看!!!" },
new Book() { Id="2", Name ="C# 高级编程",Price="66",Des="好看!!!" },
new Book() { Id="3", Name ="C# ",Price="666",Des="好看!!!" },
};
// GET: /api/Book
public IEnumerable<Book> Get()
{
return listBooks;
}
// GET: /api/Book/5
public Book Get(string id) //形参名称必须得是 id
{
return listBooks.Where(t=>t.Id==id).First();
}
[HttpGet]
public Book GetBookByPrice(string prices)
{
return listBooks.Where(t => t.Price == prices).First();
}
// POST: /api/Book
[HttpPost]
public void Post([FromBody]Book book)
{
listBooks.Add(book);
}
// PUT: api/Book/5
[HttpPut]
public Book Put(string id, [FromBody]Book value)
{
Book book= listBooks.Where(t => t.Id ==id).First();
book.Id = value.Id;
book.Name = value.Name;
book.Price = value.Price;
book.Des = value.Des;
return book;
}
// DELETE: api/Book/5
[HttpDelete]
public void Delete(int id)
{
listBooks.RemoveAt(id + 1);
}
}
注意访问修饰符需要 Public
如果指定查询条件,那么在访问时需要这样访问 , http://localhost:50610/api/Book?Price=66
,参数名必须对应
[HttpGet]
public List<Book> GetBookByPrice(string price)
{
return listBooks.Where(t => t.Price == price).ToList();
}
3.如果使用Linq 查询,那么返回结果可以使用DataTable
<1>将IQueryable 转换为 DataTable
public static DataTable ToDataTable(IQueryable source, DBDataContext db)
{
if(db.Connection.State== ConnectionState.Closed)
{
db.Connection.Open();
}
DataTable dt = new DataTable();
dt.Load(db.GetCommand(source).ExecuteReader());
db.Connection.Close();
return dt;
}
<2> 将IEnumerable装换为DataTable
// IEnumerable 转换为一个DataTable
public static DataTable ToDataTable(IEnumerable list)
{
//创建属性的集合
List<PropertyInfo> pList = new List<PropertyInfo>();
//获得反射的入口
Type type = list.AsQueryable().ElementType;
DataTable dt = new DataTable();
//把所有的public属性加入到集合 并添加DataTable的列
Array.ForEach<PropertyInfo>(type.GetProperties(), p => { pList.Add(p); dt.Columns.Add(p.Name, p.PropertyType); });
foreach (var item in list)
{
//创建一个DataRow实例
DataRow row = dt.NewRow();
//给row 赋值
pList.ForEach(p => row[p.Name] = p.GetValue(item, null));
//加入到DataTable
dt.Rows.Add(row);
}
return dt;
}
文章部分内容摘自网络和图书,如有侵权,请联系我。