using System;
using System.Collections.Generic;using System.Linq;using System.Net;using System.Web.Http;namespace iAttendance.Controllers
{ public class UsersController : ApiController { // GET api/users public IEnumerable<Users> GetUserList() { using (iAttendanceDataContext db = new iAttendanceDataContext()) { return db.Users.AsQueryable(); } }// GET api/users/5
public Users GetUser(int id) { using (iAttendanceDataContext db = new iAttendanceDataContext()) { return db.Users.FirstOrDefault(u=>u.UserID==id); } }// POST api/users
public void PostUser(Users user) { using (iAttendanceDataContext db = new iAttendanceDataContext()) { db.Users.InsertOnSubmit(user); db.SubmitChanges(); } }// PUT api/users/5
public void PutUser(int id, Users user) { using (iAttendanceDataContext db = new iAttendanceDataContext()) { var use = db.Users.SingleOrDefault(u => u.UserID == id); if (use != null) { use.Role = user.Role; use.Password = user.Password; use.Email = user.Email;db.SubmitChanges();
} } } // PUT api/users/5 public void put_nomorl_user(int id, Users user) { using (iAttendanceDataContext db = new iAttendanceDataContext()) { var use = db.Users.SingleOrDefault(u => u.UserID == id); if (use != null) { use.Role = user.Role; use.Password = user.Password; use.Email = user.Email;db.SubmitChanges();
} } }// DELETE api/users/5
public void DeleteUset(int id) { using (iAttendanceDataContext db = new iAttendanceDataContext()) { var user = db.Users.SingleOrDefault(u => u.UserID == id); if (user != null) { db.Users.DeleteOnSubmit(user); db.SubmitChanges(); } } } // [HttpGet] // public IEnumerable<Customer> SelectAllCustomers() // { //... // }// [HttpGet]
// public Customer SelectCustomerByID(string id) // { //... // }// [HttpPost]
// public string AddCustomer(Customer obj) // { //... // }// [HttpPut]
// public string ModifyCustomer(string id, Customer obj) // { //... // }// [HttpDelete]
// public string RemoveCustomer(string id) // { //... // } }}using System;
using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Security;using System.Web.SessionState;using System.Web.Routing;using System.Web.Http;using System.Web.Mvc;namespace iAttendance
{ public class Global : System.Web.HttpApplication { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); }public static void RegisterRoutes(RouteCollection routes)
{ routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); }public static void Register(HttpConfiguration config)
{ config.Routes.MapHttpRoute( name: "VersionActionApi", routeTemplate: "api/1/{controller}/{action}/{id}",//api/version/controller/action/id defaults: new { id = RouteParameter.Optional } );config.Routes.MapHttpRoute(
name: "ActionApi", routeTemplate: "api/{controller}/{action}/{id}",//api/version/type/controller/action/id defaults: new { id = RouteParameter.Optional } );config.Routes.MapHttpRoute(
name: "VersionApi", routeTemplate: "api/1/{controller}/{id}",//api/version/controller/id defaults: new { id = RouteParameter.Optional } );config.Routes.MapHttpRoute(
name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); }void Application_Start(object sender, EventArgs e)
{ // 在应用程序启动时运行的代码 Register(GlobalConfiguration.Configuration); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); }void Application_End(object sender, EventArgs e)
{ // 在应用程序关闭时运行的代码}
void Application_Error(object sender, EventArgs e)
{ // 在出现未处理的错误时运行的代码}
void Session_Start(object sender, EventArgs e)
{ // 在新会话启动时运行的代码}
void Session_End(object sender, EventArgs e)
{ // 在会话结束时运行的代码。}
}
}
using System;
using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using RestSharp;using RestSharp.Serializers;namespace iAttendWinFrm
{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void ThreadSafe(Control control, MethodInvoker function) { if ((function != null) && (control != null)) { if (control.InvokeRequired) { control.Invoke(function); } else { function(); } } }private void button1_Click(object sender, EventArgs e)
{ try { var client = new RestClient("http://localhost"); var request = new RestRequest("api/users", Method.GET); var response = client.Execute(request); this.textBox1.Text = response.Content; } catch (Exception ex) { throw ex; } } private void button2_Click(object sender, EventArgs e) { try { var client = new RestClient("http://localhost"); var request = new RestRequest() { Resource = "api/users", Method = Method.GET, RequestFormat = DataFormat.Json}; client.ExecuteAsync(request, response => { this.ThreadSafe(this, () => { this.textBox1.Text = response.Content; }); }); } catch (Exception ex) { throw ex; } }private void button3_Click(object sender, EventArgs e)
{ try { var client = new RestClient("http://localhost"); var request = new RestRequest("api/users/{id}", Method.GET); request.AddParameter("id", "1"); var response = client.Execute(request); this.textBox1.Text = response.Content; } catch (Exception ex) { throw ex; } }private void button4_Click(object sender, EventArgs e)
{ try { var client = new RestClient("http://localhost"); var request = new RestRequest() { Resource = "api/users/{id}", Method = Method.GET, RequestFormat = DataFormat.Json }; request.AddParameter("id", "1"); client.ExecuteAsync(request, response => { this.ThreadSafe(this, () => { this.textBox1.Text = response.Content; }); }); } catch (Exception ex) { throw ex; } }private void button5_Click(object sender, EventArgs e)
{ try { var client = new RestClient("http://localhost"); //var request = new RestRequest() { Resource = "api/1/user/users", Method = Method.POST, RequestFormat = DataFormat.Json }; var request = new RestRequest() { Resource = "api/1/users", Method = Method.POST, RequestFormat = DataFormat.Json }; request.AddBody(new { Email = "fx@163.com", Password = "111111", Role = 0, UserID=string.Empty,UserName = "5555555555" }); var response = client.Execute(request); this.textBox1.Text = response.Content; } catch (Exception ex) { throw ex; } }private void button8_Click(object sender, EventArgs e)
{ try { var client = new RestClient("http://localhost"); var request = new RestRequest() { Resource = "api/users", Method = Method.POST, RequestFormat = DataFormat.Json }; request.AddBody(new { Email = "fx@163.com", Password = "2235425325", Role = 0, UserID = string.Empty, UserName = "77777777" }); client.ExecuteAsync(request, response => { this.ThreadSafe(this, () => { this.textBox1.Text = response.Content; }); }); } catch (Exception ex) { throw ex; } }private void button6_Click(object sender, EventArgs e)
{ try { var client = new RestClient("http://localhost"); //var request = new RestRequest() { Resource = "api/users/PutUser/{id}", Method = Method.PUT, RequestFormat = DataFormat.Json }; //var request = new RestRequest() { Resource = "api/1/users/PutUser/{id}", Method = Method.PUT, RequestFormat = DataFormat.Json }; var request = new RestRequest() { Resource = "api/1/users/put_nomorl_user/{id}", Method = Method.PUT, RequestFormat = DataFormat.Json }; request.AddUrlSegment("id", "11"); request.AddParameter("Email", "6666666@163.com"); request.AddParameter("Password", "666666666"); request.AddParameter("Role", 1); var response = client.Execute(request); this.textBox1.Text = response.Content; } catch (Exception ex) { throw ex; } }private void button7_Click(object sender, EventArgs e)
{ try { var client = new RestClient("http://localhost"); var request = new RestRequest() { Resource = "api/users/{id}", Method = Method.PUT, RequestFormat = DataFormat.Json }; request.AddUrlSegment("id", "14"); request.AddParameter("Email", "fxxx@163.com"); request.AddParameter("Password", "1324324234"); request.AddParameter("Role", 1); client.ExecuteAsync(request, response => { this.ThreadSafe(this, () => { this.textBox1.Text = response.Content; }); }); } catch (Exception ex) { throw ex; } }private void button9_Click(object sender, EventArgs e)
{ try { var client = new RestClient("http://localhost"); var request = new RestRequest() { Resource = "api/users/{id}", Method = Method.DELETE, RequestFormat = DataFormat.Json }; request.AddUrlSegment("id", "15"); var response = client.Execute(request); this.textBox1.Text = response.Content; } catch (Exception ex) { throw ex; } }private void button10_Click(object sender, EventArgs e)
{ try { var client = new RestClient("http://localhost"); var request = new RestRequest() { Resource = "api/users/{id}", Method = Method.DELETE, RequestFormat = DataFormat.Json }; request.AddUrlSegment("id", "15"); client.ExecuteAsync(request, response => { this.ThreadSafe(this, () => { this.textBox1.Text = response.Content; }); }); } catch (Exception ex) { throw ex; } }}}
//-------------------------------------------------------------------
默认的规则
在ASP.NET MVC4中
global.asax.cs代码中并无注册默认路由规则的代码
代码如下:
public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } }
那么默认的路由规则是在哪里注册的呢?
我们发现
在项目中多了一个App_Start文件夹
其中RoteConfig.cs文件就是注册默认路由规则的程序所在了
代码如下:
public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); }
这里有两个路由规则
一个是针对API请求的路由规则
另一个是针对普通MVC页面请求的路由规则
请求路径以字符串”api”开头的时候将访问webAPI的函数
(注:至于为什么用MapHttpRoute而不是MapRoute;为什么用routeTemplate而不是用url我们再以后的章节介绍)
因为routeTemplate中有了{controller}
所以针对api的请求可以自动映射到指定的controller类
那么是怎么找到合适的Action的呢?
系统根据请求的方式来判断
如果是以GET的方式请求的
那么将匹配controller中以“Get”开头的Action
如果是以POST的方式请求的
那么将匹配controller中以“Post”开头的Action
如果是以PUT的方式请求的
那么将匹配controller中以“Put”开头的Action
如果是以DELETE的方式请求的
那么将匹配controller中以“Delete”开头的Action
除了这几个默认的请求方式
你还可以在客户端定义你自己的请求方式!
routeTemplate最后面的id匹配Action中的参数,
这与ASP.NET MVC一致
初步的自定义
那么是不是所有的匹配GET请求的Action都必须以“Get”开头呢
不是的
我们可以用方法特性来标记一个方法属于什么什么请求
如下:
[HttpGet] public IEnumerableAllProducts() { return products; }
对应的方法特性还有
[HttpPost]
[HttpDelete]
[HttpPut]
亦可以使用如下这样的方法特性来区分
[AcceptVerbs("GET")]
[AcceptVerbs("GET", "HEAD")]
另外如果你在Controller中写了一个函数
必须是public的,必须以Get开头
而又不想让客户端以请求到此Action
那么可以使用方法特性
[NonAction]
来标记此方法
进一步自定义
我们仍然可以把action的名字放到默认的请求规则中
只要把routeTemplate改为如下即可:
routes.MapHttpRoute( name: "ActionApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } );