1 建立解决方案 注意命名的规范 名字后面要加后缀的
2 控制器中的代码
[HTTPBasicAuthorize] public class ProductController : ApiController { //这个是Model中的类,在调用localhost:8080/api/Product/5 时一定要注意命名的规范,不然没法调用 // 控制器 ProductController.cs // 模型 ProductModels.cs ProductModels product = new ProductModels(); private readonly List<ProductModels> products = new List<ProductModels> { new ProductModels {ProductID = 1, ProductName = "张三"}, new ProductModels {ProductID = 2, ProductName = "李四"}, new ProductModels {ProductID = 3, ProductName = "王五"} }; //GET api/Product/ public IEnumerable<ProductModels> GetAllProducts() { return products; } //GET api/Product/?productId=1 传参数 public ProductModels GetProductById(int productId) { if (product == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } return products.Where(x => x.ProductID == productId).First() as ProductModels; } }
3 验证类调用API时 需要输入用户名和密码验证
//System.Web.Http.AuthorizeAttribute(身份认证类) public class HTTPBasicAuthorizeAttribute : System.Web.Http.AuthorizeAttribute { public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext) { string user = Users; string roel = Roles; object typeId = TypeId; if (actionContext.Request.Headers.Authorization != null) {//!HttpContext.Current.User.Identity.IsAuthenticated string userInfo = Encoding.Default.GetString(Convert.FromBase64String(actionContext.Request.Headers.Authorization.Parameter)); //验证用户是否合法 //if (string.Equals(userInfo, string.Format("{0}:{1}", "Parry", "123456"))) //{ // IsAuthorized(actionContext); //} //验证用户是否合法 if (!HttpContext.Current.User.Identity.IsAuthenticated) { IsAuthorized(actionContext); } else { HandleUnauthorizedRequest(actionContext); } } else { HandleUnauthorizedRequest(actionContext); } } /// <summary> /// 处理授权失败的 HTTP 请求 弹出登陆页 /// </summary> /// <param name="actionContext"></param> protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext) { var challengeMessage = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized); challengeMessage.Headers.Add("WWW-Authenticate", "Basic"); throw new System.Web.Http.HttpResponseException(challengeMessage); } //public override bool AuthorizeCore(HttpContextBase contextBase) //{ // if (contextBase.Request.Cookies["user"] == null) // { // return false; // } // return base.AuthorizeCore(contextBase); //} }
5 前台调用(没有做到Post)请求 值实现了get清求
$(function () { // $.getJSON("api/Product/", function (data) { // $.each(data, function (key, val) { // var str = val.ProductID + ': ' + val.ProductName; // alert(str); // }); // }); $.ajax({ type: "get", url: "api/Product/", data: { "productId": "1" }, success: function (msg) { alert(msg.ProductName); }, error: function (msg) { alert("请求异常"); } }); })
6 调地址是 http://localhost:xxx/api/Product/1