1 Building a solution note the name of the canonical names that are appended with the suffix
2 code in the controller
[Httpbasicauthorize] Public classProductcontroller:apicontroller {//This is the class in the model, you must pay attention to the named specification when calling LOCALHOST:8080/API/PRODUCT/5, otherwise you cannot call//Controller ProductController.cs//Model ProductModels.csProductmodels Product =Newproductmodels (); Private ReadOnlylist<productmodels> products =NewList<productmodels> { Newproductmodels {ProductID =1, ProductName ="Zhang San"}, Newproductmodels {ProductID =2, ProductName ="John Doe"}, Newproductmodels {ProductID =3, ProductName ="Harry"} }; //GET api/product/ PublicIenumerable<productmodels>getallproducts () {returnProducts ; } //GET api/product/?productid=1 Pass Parameters PublicProductmodels Getproductbyid (intproductId) { if(Product = =NULL) { Throw Newhttpresponseexception (Httpstatuscode.notfound); } returnProducts. Where (x = X.productid = = ProductID). First () asProductmodels; } }
3 Verify that the class calls the API with user name and password Authentication required
//System.Web.Http.AuthorizeAttribute (Identity authentication Class) Public classHTTPBasicAuthorizeAttribute:System.Web.Http.AuthorizeAttribute { Public Override voidonauthorization (System.Web.Http.Controllers.HttpActionContext actioncontext) {stringuser =Users; stringRoel =Roles; ObjectTypeId =TypeId; if(ActionContext.Request.Headers.Authorization! =NULL) {//! HttpContext.Current.User.Identity.IsAuthenticated stringUserInfo =Encoding.Default.GetString (convert.frombase64string (ActionContext.Request.Headers.Authorization.Parameter) ); //Verify that the user is legitimate//if (string. Equals (UserInfo, String. Format ("{0}:{1}", "Parry", "123456" )))//{ //isauthorized (Actioncontext); //} //Verify that the user is legitimate if(!HttpContext.Current.User.Identity.IsAuthenticated) {isauthorized (actioncontext); } Else{handleunauthorizedrequest (actioncontext); } } Else{handleunauthorizedrequest (actioncontext); } } /// <summary> ///HTTP request to handle authorization failure popup landing page/// </summary> /// <param name= "Actioncontext" ></param> protected Override voidhandleunauthorizedrequest (System.Web.Http.Controllers.HttpActionContext actioncontext) {varChallengemessage =NewSystem.Net.Http.HttpResponseMessage (System.Net.HttpStatusCode.Unauthorized); CHALLENGEMESSAGE.HEADERS.ADD ("www-authenticate","Basic"); Throw NewSystem.Web.Http.HttpResponseException (challengemessage); } //Public override bool Authorizecore (HttpContextBase contextbase)//{ //if (contextbase.request.cookies["user"] = = null)// { //return false; // } //return base. Authorizecore (contextbase); //}}
5 Reception Call (no post) Request value implemented get clear
$ (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 ("Request Exception"); } }); })
The 6-tone address is HTTP://LOCALHOST:XXX/API/PRODUCT/1.
WBEAPI Study Notes