.Net WebApi基本操作

一、服务端

1.新建webapi项目

2.配置WebApiConfig

public const string DEFAULT_ROUTE_NAME = "DB";// DB指数据库上下文
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DEFAULT_ROUTE_NAME",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.EnableSystemDiagnosticsTracing();
}

3.在models文件新建studentInfo模型

[Table("studentInfo")]
public class studentInfo
{
[Key]
public int Id { get; set; }
/// <summary>
/// 学号
/// </summary>
public int studentId { get; set; }
/// <summary>
/// 学生姓名
/// </summary>
public string studentName { get; set; }
/// <summary>
/// 联系方式
/// </summary>
public string contact { get; set; }
}

4.在models文件中添加DB,数据库上下文, DB要继承DbContext

          public DbSet<studentInfo> sInfo { get; set; }

5.在models文件中添加接口IstudentRepository

 

/// <summary>
/// 获得所有人
/// </summary>
/// <returns></returns>
IEnumerable<studentInfo> GetAll();
/// <summary>
/// 根据ID查询
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
studentInfo Get(int id);
/// <summary>
/// 添加
/// </summary>
/// <param name="person"></param>
/// <returns></returns>
studentInfo Add(studentInfo info);
/// <summary>
/// 删除
/// </summary>
/// <param name="id"></param>
void Remove(int id);
/// <summary>
/// 更新
/// </summary>
/// <param name="person"></param>
/// <returns></returns>
bool Update(studentInfo info);

 

 6.在models文件中添加仓库实现studentRepository

 

public class studentRepository : IstudentRepository
{
DB db = new DB();
private List<studentInfo> _people = new List<studentInfo>();

 

public IEnumerable<studentInfo> GetAll()
{
var model = db.sInfo.OrderByDescending(c => c.Id).ToList();
return model;
}

 

public studentInfo Get(int id)
{
var queryData = db.sInfo.FirstOrDefault(c => c.Id == id);

 

return queryData;
}

 

public studentInfo Add(studentInfo info)
{
if (info == null)
{

 

throw new ArgumentNullException("info");

 

}

 

var addmodel = db.sInfo.Add(info);
db.SaveChanges();
return addmodel;
}

 

public void Remove(int id)
{

 

var model = db.sInfo.Find(id);
db.sInfo.Remove(model);
db.SaveChanges();

 

}

 

public bool Update(studentInfo Info)
{
if (Info == null)
{

 


return false;
}

 


else
{
var model = db.sInfo.FirstOrDefault(c => c.Id == Info.Id);
model.studentId = Info.studentId;
model.studentName = Info.studentName;
model.contact = Info.contact;
var entry = db.Entry(model);
entry.Property(c => c.studentId).IsModified = true;
entry.Property(c => c.contact).IsModified = true;

 

entry.Property(c => c.studentName).IsModified = true;
db.SaveChanges();

return true;
}

 

}
}

 7.配置web.config

<add name="DB" providerName="System.Data.SqlClient" connectionString="Data Source=.;Initial Catalog=WebApiDB;Integrated Security=SSPI; User ID=sa; password=123456" />

8.在controllers中添加apiController为PersonController

static readonly IstudentRepository databasePlaceholder = new studentRepository();
/// <summary>
/// 所有人数
/// </summary>
/// <returns></returns>
public IEnumerable<studentInfo> GetAllPeople()
{
return databasePlaceholder.GetAll();
}

/// <summary>
/// 查询
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public studentInfo GetPersonByID(int id)
{
studentInfo person = databasePlaceholder.Get(id);
if (person == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return person;
}
/// <summary>
/// 添加
/// </summary>
/// <param name="person"></param>
/// <returns></returns>
public HttpResponseMessage PostPerson(studentInfo person)
{
person = databasePlaceholder.Add(person);
string apiName = MyWebApiDemo.WebApiConfig.DEFAULT_ROUTE_NAME;
var response = this.Request.CreateResponse<studentInfo>(HttpStatusCode.Created, person);
string uri = Url.Link(apiName, new { id = person.Id });
response.Headers.Location = new Uri(uri);
return response;
}
/// <summary>
/// 更新
/// </summary>
/// <param name="person"></param>
/// <returns></returns>
public bool PutPerson(studentInfo person)
{
if (!databasePlaceholder.Update(person))
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return true;

}
/// <summary>
/// 删除
/// </summary>
/// <param name="id"></param>
public void DeletePerson(int id)
{

studentInfo person = databasePlaceholder.Get(id);

if (person == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}

databasePlaceholder.Remove(id);


}

二、客户端

private const string url = "http://localhost:50043/";
public ActionResult Index()
{
List<studentInfo> people = GetAllPerson();
return View(people);
}
/// <summary>
/// 获得所有学生信息
/// </summary>
/// <returns></returns>
static List<studentInfo> GetAllPerson()
{
HttpClient client = new HttpClient();
HttpResponseMessage response = client.GetAsync(url + "api/person").Result;
return response.Content.ReadAsAsync<List<studentInfo>>().Result;
}
public ActionResult Delete(int id)
{
DeletePerson(id);
return RedirectToAction("Index");
}
/// <summary>
/// 删除
/// </summary>
/// <param name="id"></param>
static void DeletePerson(int id)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(url);
var relativeUri = "api/person/" + id.ToString();
var response = client.DeleteAsync(relativeUri).Result;
client.Dispose();
}
static studentInfo GetPerson(int id)
{
HttpClient client = new HttpClient();
HttpResponseMessage response = client.GetAsync(url + "api/person/" + id).Result;

return response.Content.ReadAsAsync<studentInfo>().Result;
}


public ActionResult Update(int id)
{
studentInfo model = GetPerson(id);
return View(model);
}
[HttpPost]
public ActionResult Update(studentInfo info)
{

UpdatePerson(info);

return RedirectToAction("Index");
}

static bool UpdatePerson(studentInfo info)
{


HttpClient client = new HttpClient();
client.BaseAddress = new Uri(url);
var response = client.PutAsJsonAsync("api/person", info).Result;
bool b= response.Content.ReadAsAsync<bool>().Result;
return b;
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(studentInfo info)
{
JObject newPerson = AddPerson(info);
return RedirectToAction("Index");
}
static JObject AddPerson(studentInfo info)
{

HttpClient client = new HttpClient();

client.BaseAddress = new Uri(url);

var response = client.PostAsJsonAsync("api/person", info).Result;

return response.Content.ReadAsAsync<JObject>().Result;

}

 

posted @ 2016-03-07 17:22  装饰的梦  阅读(431)  评论(0编辑  收藏  举报