1.Restful风格:
Get/Post/Put/Delete 语义关键字必须再方法最前面,譬如GetStudent;
不能在其他部分,譬如HelloGetStudent、StudentGet; 方法名称也可以只包含语义关键字,譬如 public void Get(){};
2.定制路由-路由特性
RoutePrefix:[RoutePrefix(prefix: "api/UserLogin")] 路由前缀
[Route(template: "AjaxLogin")] 路由模板
通过定制路由前缀和路由模板,可以不通过Restful风格调用后台,实现类似MVC的action调用方式
namespace WebApplication1.Controllers { [RoutePrefix(prefix: "api/UserLogin")] public class UserLoginController : ApiController { [Route(template: "Login")] [HttpGet] public string Login([FromUri] UserInfo userinfo) { return "UrlOK"; } [Route(template: "AjaxLogin")] [HttpPost] public string AjaxLogin([FromBody] UserInfo userinfo) { return "AjaxOK"; } } }
启用调用方式有
1.Url:get方式调用:http://localhost:8222/api/UserLogin/Login?userinfo="{UserName:zhangsan,UserPwd:123}",参数要保证与方法Login一致;以Url方式调用,方法需要加上特性【HttpGet】,方法参数需要加上特性【FromUri】;
2.Ajax:post方式调用,如下代码;以Ajax方式调用,方法可以加上(非必须,ajax get方法也可以请求) 特性【HttpPost】,方法参数可以加上(非必须,ajax get方法也可以请求) 特性【FromBody】;
$.ajax({ url: "/api/UserLogin/AjaxLogin", type: "post", data: { UserName: "wangwu", UserPwd: "123" } }).done(function (data) { console.log(data); })
3.关于请求参数
3.1 路由请求规则
namespace WebApplication1.Controllers { public class StudentsController : ApiController { public string Get() { return "默认的get方法"; } public string Get(string name) { return "您输入的参数name为" + name; } public string GetAddress1(string address2) { return "您输入的地址参数address为" + address2; } } }
3.1.1 如上路由,只有请求地址http://localhost:8222/api/Students?address2=zhangsan才有效,注意QueryString里面是根据【参数名称:address2】找对应的action,不是【函数名称Address1】;
3.1.2 或者使用ajax请求如下,注意webapi的路由规则为api/{controller}/{id},没有{action};MVC的路由规则为{controller}/{action}/{id}有{action};找不到对应的参数名就会寻找默认的Get方法,注意如果都是Get请求,不能有相同的参数名称,否则会报错:【ExceptionMessage: "找到了与该请求匹配的多个操作】
$.ajax({ url: "/api/Students", type: "get", data: { name: "123" } }).done(function (data) { console.log(data); })
3.2 Get/Post请求参数
3.2.1 Get请求
function btnLogin() { //单参数传值 var name = document.getElementById("loginName").value; var pwd = document.getElementById("loginPwd").value; $.ajax({ url: "../api/Values/LoginGetJson", type: "get", data: { "model": JSON.stringify(new Object({ UserName: name, UserPwd: pwd })) }, success: function (data) { console.log("LoginGetJson:" + data); } , error: function (msg) { console.log("LoginGetJson:" + msg.responseJSON.ExceptionMessage); } }) $.ajax({ //多参数传值 url: "../api/Values/LoginGetMultipleParam", type: "get", data: { UserName: name, UserPwd: pwd }, success: function (data) { console.log("LoginGetMultipleParam:" + data); } , error: function (msg) { console.log("LoginGetMultipleParam:" + msg.responseJSON.ExceptionMessage); } }) $.ajax({ //对象传值 url: "../api/Values/LoginGetObj", type: "get", data: { UserName: name, UserPwd: pwd }, success: function (data) { console.log("LoginGetObj:" + data); } , error: function (msg) { console.log("LoginGetObj:" + msg.responseJSON.ExceptionMessage); } })
[Route("LoginGetJson")] //单参数传值 [HttpGet] public string LoginGetJson(string model) { try { UserViewModel userModel = JsonConvert.DeserializeObject<UserViewModel>(model); if (userModel.UserName.Length >= 2 && userModel.UserPwd.Equals("123456")) { return "true"; } return "false:账号密码校验失败"; } catch (Exception ex) { return "false:" + ex.Message; } } [Route("LoginGetMultipleParam")] //多参数传值 [HttpGet] public string LoginGetMultipleParam(string userName, string userPwd) { try { if (userName.Length >= 2 && userPwd.Equals("123456")) { return "true"; } return "false:账号密码校验失败"; } catch (Exception ex) { return "false:" + ex.Message; } } [Route("LoginGetObj")] //对象传值 [HttpGet] public string LoginGetObj([FromUri] UserViewModel model) { try { if (model.UserName.Length >= 2 && model.UserPwd.Equals("123456")) { return "true"; } return "false:账号密码校验失败"; } catch (Exception ex) { return "false:" + ex.Message; } }
3.2.2 Post请求
[Route("LoginPostJson")] //单参数传值 [HttpPost] public string LoginPostJson([FromBody] string model) { try { UserViewModel userModel = JsonConvert.DeserializeObject<UserViewModel>(model); if (userModel.UserName.Length >= 2 && userModel.UserPwd.Equals("123456")) { return "true"; } return "false:账号密码校验失败"; } catch (Exception ex) { return "false:" + ex.Message; } } [Route("LoginPostMultipleParam")] //多参数传值(无法实现) [HttpPost] public string LoginPostMultipleParam([FromBody] string userName, [FromBody] string userPwd) { try { if (userName.Length >= 2 && userPwd.Equals("123456")) { return "true"; } return "false:账号密码校验失败"; } catch (Exception ex) { return "false:" + ex.Message; } } [Route("LoginPostObj")] //对象传值 [HttpPost] public string LoginPostObj(UserViewModel model) { try { if (model.UserName.Length >= 2 && model.UserPwd.Equals("123456")) { return "true"; } return "false:账号密码校验失败"; } catch (Exception ex) { return "false:" + ex.Message; } } [Route("LoginPostDynamic")] //动态类传值 [HttpPost] public string LoginPostDynamic(dynamic model) { try { if (((string)model.UserName).Length >= 2 && ((string)model.UserPwd).Equals("123456")) { return "true"; } return "false:账号密码校验失败"; } catch (Exception ex) { return "false:" + ex.Message; } }
$.ajax({ //单参数传值 url: "../api/Values/LoginPostJson", type: "post", data: { "": JSON.stringify(new Object({ UserName: name, UserPwd: pwd })) }, success: function (data) { console.log("LoginPostJson:" + data); } , error: function (msg) { console.log("LoginPostJson:" + msg.responseJSON.ExceptionMessage); } }) $.ajax({ //多参数传值(无法实现) url: "../api/Values/LoginPostMultipleParam", type: "post", data: { "": name, "": pwd }, success: function (data) { console.log("LoginPostMultipleParam:" + data); } , error: function (msg) { console.log("LoginPostMultipleParam:" + msg.responseJSON.ExceptionMessage); } }) $.ajax({ //对象传值 url: "../api/Values/LoginPostObj", type: "post", data: { UserName: name, UserPwd: pwd }, success: function (data) { console.log("LoginPostObj:" + data); } , error: function (msg) { console.log("LoginPostObj:" + msg.responseJSON.ExceptionMessage); } }) $.ajax({ //动态类传值 url: "../api/Values/LoginPostDynamic", type: "post", contentType:"application/json", data: JSON.stringify(new Object({ "UserName": name, "UserPwd": pwd })), success: function (data) { console.log("LoginPostDynamic:" + data); } , error: function (msg) { console.log("LoginPostDynamic:" + msg.responseJSON.ExceptionMessage); } })
3.2.3 总结:
3.2.3.1 Get请求支持 单参数传值 / 多参数传值 / 对象传值;Post请求支持 单参数传值 / 对象传值 / 动态类传值;Get不支持动态类传值,如果实现了其实也是跟单参数string传值一样,在后台做了JsonConvert.DeserializeObject反序列化操作;
3.2.3.2 Get请求的对象传值,在后台参数加了特性[FromUrl];Post请求的单参数传值,在后台参数加了特性[FromBody];个人理解非对象类基类型参数默认从Url拿值,对象类参数默认从Body拿值,否则需要特殊申明;
4.其他
4.1 不能直接访问根目录下Views文件夹里面的文件(静态文件);
需要在Views文件夹下的web.config中配置(如果需要添加CSS文件,则另加一行,类似JS的配置)
<remove name="BlockViewHandler"/>
<add name="js" verb="GET,HEAD" path="*.js" type="System.Web.StaticFileHandler" />