- WebApi前台调用详析
由于方法很多,控制器里面没有遵循restful--增加一个类似mvc的路由
config.Routes.MapHttpRoute( name: "CustomApi",//自定义api路由,要写在默认路由前。 routeTemplate: "api/{controller}/{action}/{id}",//正则规则,以api开头,第二个是控制器 第三个是action(方法名),第四个是参数 defaults: new { id = RouteParameter.Optional } );
UI对方法的AJAX调用
建立控制器 UsersController
public class UsersController : ApiController { private IUserService _IUserService = null; public UsersController(IUserService userService) { this._IUserService = userService; } ////// User Data List /// private List_userList = new List { new Users {UserID = 1, UserName = "Superman", UserEmail = "Superman@cnblogs.com"}, new Users {UserID = 2, UserName = "Spiderman", UserEmail = "Spiderman@cnblogs.com"}, new Users {UserID = 3, UserName = "Batman", UserEmail = "Batman@cnblogs.com"} }; #region 用户登陆 //[CustomAllowAnonymousAttribute] [HttpGet] public string Login(string account, string password) { if ("Admin".Equals(account) && "123456".Equals(password))//应该数据库校验 { FormsAuthenticationTicket ticketObject = new FormsAuthenticationTicket(0, account, DateTime.Now, DateTime.Now.AddHours(1), true, string.Format("{0}&{1}", account, password), FormsAuthentication.FormsCookiePath); var result = new { Result = true, Ticket = FormsAuthentication.Encrypt(ticketObject) }; return JsonConvert.SerializeObject(result); } else { var result = new { Result = false }; return JsonConvert.SerializeObject(result); } } #endregion #region HttpGet // GET api/Users [HttpGet] public IEnumerable Get() { return _userList; } // GET api/Users/5 [HttpGet] //[AllowAnonymous] //[EnableCors(origins: "http://localhost:9008/", headers: "*", methods: "GET,POST,PUT,DELETE")] //[CustomBasicAuthorizeAttribute]//方法注册 public Users GetUserByID(int id) { string idParam = HttpContext.Current.Request.QueryString["id"]; var user = _userList.FirstOrDefault(users => users.UserID == id); if (user == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } return user; } //GET api/Users/?username=xx [HttpGet] //[CustomBasicAuthorizeAttribute] public IEnumerable GetUserByName(string userName) { string userNameParam = HttpContext.Current.Request.QueryString["userName"]; return _userList.Where(p => string.Equals(p.UserName, userName, StringComparison.OrdinalIgnoreCase)); } //GET api/Users/?username=xx&id=1 [HttpGet] public IEnumerable GetUserByNameId(string userName, int id) { string idParam = HttpContext.Current.Request.QueryString["id"]; string userNameParam = HttpContext.Current.Request.QueryString["userName"]; return _userList.Where(p => string.Equals(p.UserName, userName, StringComparison.OrdinalIgnoreCase)); } [HttpGet] public IEnumerable GetUserByModel(Users user) { string idParam = HttpContext.Current.Request.QueryString["id"]; string userNameParam = HttpContext.Current.Request.QueryString["userName"]; string emai = HttpContext.Current.Request.QueryString["email"]; return _userList; } [HttpGet] public IEnumerable GetUserByModelUri([FromUri]Users user) { string idParam = HttpContext.Current.Request.QueryString["id"]; string userNameParam = HttpContext.Current.Request.QueryString["userName"]; string emai = HttpContext.Current.Request.QueryString["email"]; return _userList; } [HttpGet] public IEnumerable GetUserByModelSerialize(string userString) { Users user = JsonConvert.DeserializeObject (userString); return _userList; } //[HttpGet] public IEnumerable GetUserByModelSerializeWithoutGet(string userString) { Users user = JsonConvert.DeserializeObject (userString); return _userList; } /// /// 方法名以Get开头,WebApi会自动默认这个请求就是get请求,而如果你以其他名称开头而又不标注方法的请求方式,那么这个时候服务器虽然找到了这个方法,但是由于请求方式不确定,所以直接返回给你405——方法不被允许的错误。 /// 最后结论:所有的WebApi方法最好是加上请求的方式([HttpGet]/[HttpPost]/[HttpPut]/[HttpDelete]),不要偷懒,这样既能防止类似的错误,也有利于方法的维护,别人一看就知道这个方法是什么请求。 /// /// ///public IEnumerable NoGetUserByModelSerializeWithoutGet(string userString) { Users user = JsonConvert.DeserializeObject (userString); return _userList; } #endregion HttpGet #region HttpPost //POST api/Users/RegisterNone [HttpPost] public Users RegisterNone() { return _userList.FirstOrDefault(); } [HttpPost] public Users RegisterNoKey([FromBody]int id) { string idParam = HttpContext.Current.Request.Form["id"]; var user = _userList.FirstOrDefault(users => users.UserID == id); if (user == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } return user; } //POST api/Users/register //只接受一个参数的需要不给key才能拿到 [HttpPost] public Users Register([FromBody]int id)//可以来自FromBody FromUri //public Users Register(int id)//可以来自url { string idParam = HttpContext.Current.Request.Form["id"]; var user = _userList.FirstOrDefault(users => users.UserID == id); if (user == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } return user; } //POST api/Users/RegisterUser [HttpPost] public Users RegisterUser(Users user)//可以来自FromBody FromUri { string idParam = HttpContext.Current.Request.Form["UserID"]; string nameParam = HttpContext.Current.Request.Form["UserName"]; string emailParam = HttpContext.Current.Request.Form["UserEmail"]; //var userContent = base.ControllerContext.Request.Content.ReadAsFormDataAsync().Result; var stringContent = base.ControllerContext.Request.Content.ReadAsStringAsync().Result; return user; } //POST api/Users/register [HttpPost] public string RegisterObject(JObject jData)//可以来自FromBody FromUri { string idParam = HttpContext.Current.Request.Form["User[UserID]"]; string nameParam = HttpContext.Current.Request.Form["User[UserName]"]; string emailParam = HttpContext.Current.Request.Form["User[UserEmail]"]; string infoParam = HttpContext.Current.Request.Form["info"]; dynamic json = jData; JObject jUser = json.User; string info = json.Info; var user = jUser.ToObject (); return string.Format("{0}_{1}_{2}_{3}", user.UserID, user.UserName, user.UserEmail, info); } [HttpPost] public string RegisterObjectDynamic(dynamic dynamicData)//可以来自FromBody FromUri { string idParam = HttpContext.Current.Request.Form["User[UserID]"]; string nameParam = HttpContext.Current.Request.Form["User[UserName]"]; string emailParam = HttpContext.Current.Request.Form["User[UserEmail]"]; string infoParam = HttpContext.Current.Request.Form["info"]; dynamic json = dynamicData; JObject jUser = json.User; string info = json.Info; var user = jUser.ToObject (); return string.Format("{0}_{1}_{2}_{3}", user.UserID, user.UserName, user.UserEmail, info); } #endregion HttpPost #region HttpPut //POST api/Users/RegisterNonePut [HttpPut] public Users RegisterNonePut() { return _userList.FirstOrDefault(); } [HttpPut] public Users RegisterNoKeyPut([FromBody]int id) { string idParam = HttpContext.Current.Request.Form["id"]; var user = _userList.FirstOrDefault(users => users.UserID == id); if (user == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } return user; } //POST api/Users/registerPut //只接受一个参数的需要不给key才能拿到 [HttpPut] public Users RegisterPut([FromBody]int id)//可以来自FromBody FromUri //public Users Register(int id)//可以来自url { string idParam = HttpContext.Current.Request.Form["id"]; var user = _userList.FirstOrDefault(users => users.UserID == id); if (user == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } return user; } //POST api/Users/RegisterUserPut [HttpPut] public Users RegisterUserPut(Users user)//可以来自FromBody FromUri { string idParam = HttpContext.Current.Request.Form["UserID"]; string nameParam = HttpContext.Current.Request.Form["UserName"]; string emailParam = HttpContext.Current.Request.Form["UserEmail"]; //var userContent = base.ControllerContext.Request.Content.ReadAsFormDataAsync().Result; var stringContent = base.ControllerContext.Request.Content.ReadAsStringAsync().Result; return user; } //POST api/Users/registerPut [HttpPut] public string RegisterObjectPut(JObject jData)//可以来自FromBody FromUri { string idParam = HttpContext.Current.Request.Form["User[UserID]"]; string nameParam = HttpContext.Current.Request.Form["User[UserName]"]; string emailParam = HttpContext.Current.Request.Form["User[UserEmail]"]; string infoParam = HttpContext.Current.Request.Form["info"]; dynamic json = jData; JObject jUser = json.User; string info = json.Info; var user = jUser.ToObject (); return string.Format("{0}_{1}_{2}_{3}", user.UserID, user.UserName, user.UserEmail, info); } [HttpPut] public string RegisterObjectDynamicPut(dynamic dynamicData)//可以来自FromBody FromUri { string idParam = HttpContext.Current.Request.Form["User[UserID]"]; string nameParam = HttpContext.Current.Request.Form["User[UserName]"]; string emailParam = HttpContext.Current.Request.Form["User[UserEmail]"]; string infoParam = HttpContext.Current.Request.Form["info"]; dynamic json = dynamicData; JObject jUser = json.User; string info = json.Info; var user = jUser.ToObject (); return string.Format("{0}_{1}_{2}_{3}", user.UserID, user.UserName, user.UserEmail, info); } #endregion HttpPut #region HttpDelete //POST api/Users/RegisterNoneDelete [HttpDelete] public Users RegisterNoneDelete() { return _userList.FirstOrDefault(); } [HttpDelete] public Users RegisterNoKeyDelete([FromBody]int id) { string idParam = HttpContext.Current.Request.Form["id"]; var user = _userList.FirstOrDefault(users => users.UserID == id); if (user == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } return user; } //POST api/Users/registerDelete //只接受一个参数的需要不给key才能拿到 [HttpDelete] public Users RegisterDelete([FromBody]int id)//可以来自FromBody FromUri //public Users Register(int id)//可以来自url { string idParam = HttpContext.Current.Request.Form["id"]; var user = _userList.FirstOrDefault(users => users.UserID == id); if (user == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } return user; } //POST api/Users/RegisterUserDelete [HttpDelete] public Users RegisterUserDelete(Users user)//可以来自FromBody FromUri { string idParam = HttpContext.Current.Request.Form["UserID"]; string nameParam = HttpContext.Current.Request.Form["UserName"]; string emailParam = HttpContext.Current.Request.Form["UserEmail"]; //var userContent = base.ControllerContext.Request.Content.ReadAsFormDataAsync().Result; var stringContent = base.ControllerContext.Request.Content.ReadAsStringAsync().Result; return user; } //POST api/Users/registerDelete [HttpDelete] public string RegisterObjectDelete(JObject jData)//可以来自FromBody FromUri { string idParam = HttpContext.Current.Request.Form["User[UserID]"]; string nameParam = HttpContext.Current.Request.Form["User[UserName]"]; string emailParam = HttpContext.Current.Request.Form["User[UserEmail]"]; string infoParam = HttpContext.Current.Request.Form["info"]; dynamic json = jData; JObject jUser = json.User; string info = json.Info; var user = jUser.ToObject (); return string.Format("{0}_{1}_{2}_{3}", user.UserID, user.UserName, user.UserEmail, info); } [HttpDelete] public string RegisterObjectDynamicDelete(dynamic dynamicData)//可以来自FromBody FromUri { string idParam = HttpContext.Current.Request.Form["User[UserID]"]; string nameParam = HttpContext.Current.Request.Form["User[UserName]"]; string emailParam = HttpContext.Current.Request.Form["User[UserEmail]"]; string infoParam = HttpContext.Current.Request.Form["info"]; dynamic json = dynamicData; JObject jUser = json.User; string info = json.Info; var user = jUser.ToObject (); return string.Format("{0}_{1}_{2}_{3}", user.UserID, user.UserName, user.UserEmail, info); } #endregion HttpDelete }
- WebApi后台调用详析
WebApi全部遵循的Http协议,HttpMethod
其实就等同于网页,可以去爬虫 就时后端模拟Http请求 可使用:HttpWebRequest HttpClient
HttpClient
using (var http = new HttpClient(handler)) 不太好 tcp其实并不能立即释放掉如果高并发式的这样操作,会出现资源不够 积极拒绝HttpClient内部有个连接池,各个请求是隔开的,可以复用链接的 实际应该单例一下要求HttpClient的实例化都从这里来 全局只要一个实例,不要using
各个请求是隔开的,可以复用链接的public class HttpClientFactory { private static HttpClient _HttpClient = null; static HttpClientFactory() { _HttpClient = new HttpClient(new HttpClientHandler()); } public static HttpClient GetHttpClient() { return _HttpClient; } }
//Get 方法 private string GetClient() { //string url = "http://localhost:8088/api/users/GetUserByName?username=superman"; var response =_HttpClient.GetAsync(url).Result;//拿到异步结果,使用单例中的实例化链接 Console.WriteLine(response.StatusCode); //确保HTTP成功状态值 //await异步读取最后的JSON(注意此时gzip已经被自动解压缩了,因为上面的AutomaticDecompression = DecompressionMethods.GZip) return response.Content.ReadAsStringAsync().Result; }//post方法private string PostClient(){string url = "http://localhost:8088/api/users/RegisterObject";Dictionarydic = new Dictionary (){{ "User[UserID]","11" },{ "User[UserName]","Eleven" },{ "User[UserEmail]","57265177@qq.com" },{ "Info","this is muti model" }};//使用FormUrlEncodedContent做HttpContentvar content = new FormUrlEncodedContent(dic);var response =_HttpClient.PostAsync(url, content).Result;Console.WriteLine(response.StatusCode); //确保HTTP成功状态值return response.Content.ReadAsStringAsync().Result;}
HttpWebRequest
////// HttpWebRequest实现Get请求 /// private string GetWebQuest() { //string url = "http://localhost:8088/api/users/GetUserByModelSerializeWithoutGet?userString=%7B%22UserID%22%3A%2211%22%2C%22UserName%22%3A%22Eleven%22%2C%22UserEmail%22%3A%2257265177%40qq.com%22%7D"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Timeout = 30 * 1000; //request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36"; //request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; string result = ""; using (var res = request.GetResponse() as HttpWebResponse) { if (res.StatusCode == HttpStatusCode.OK) { StreamReader reader = new StreamReader(res.GetResponseStream(), Encoding.UTF8); result = reader.ReadToEnd(); } } return result; } ////// HttpWebRequest实现post请求 /// private string PostWebQuest() { var user = new { UserID = "11", UserName = "Eleven", UserEmail = "57265177@qq.com" }; //string url = "http://localhost:8088/api/users/RegisterUser"; //var postData = JsonHelper.ObjectToString(user); var userOther = new { User = user, Info = "this is muti model" }; string url = "http://localhost:8088/api/users/RegisterObject"; var postData = Newtonsoft.Json.JsonConvert.SerializeObject(userOther); var request = HttpWebRequest.Create(url) as HttpWebRequest; request.Timeout = 30 * 1000;//设置30s的超时 request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36"; request.ContentType = "application/json"; request.Method = "POST"; byte[] data = Encoding.UTF8.GetBytes(postData); request.ContentLength = data.Length; Stream postStream = request.GetRequestStream(); postStream.Write(data, 0, data.Length); postStream.Close(); string result = ""; using (var res = request.GetResponse() as HttpWebResponse) { if (res.StatusCode == HttpStatusCode.OK) { StreamReader reader = new StreamReader(res.GetResponseStream(), Encoding.UTF8); result = reader.ReadToEnd(); } } return result; }
- Basic授权认证&权限Filter
//待完成