For. Net WebAPI data authentication (including login authentication and model authentication),. netwebapi
1. Use WebAPI for automatic login authentication
Automatic webApi authentication inheritance class: AuthorizeAttribute
The automatic authentication class is used on the controller.
[Authentication] public class CardController : BasisController { }View Code
Mainly rewrite two methods
1. OnAuthorization automatically calls this method during authentication
2. Call this method when HandleUnauthorizedRequest authentication fails.
/// <Summary> /// automatically authenticate the author KAI /// </summary> public class Authentication: authorizeAttribute {// <summary> // automatic authentication // </summary> /// <param name = "actionContext"> </param> public override void OnAuthorization (httpActionContext actionContext) {// actionContext: The HttpActionContext of the current request can obtain the request content // actionContext. response // actionContext. request // actionContext. requestContext // You can also obtain // System. web. http Context. current. request // System. web. httpContext. current. response if (true) {// after the request is successful, how does not use session to transmit data to the corresponding Action to set the User object of the current request? The User in the Action can directly use // HttpContext. current. user = new UserModel () {loginUser = new_user}; // set the UserModel of the current login User to the custom model base. isAuthorized (actionContext); // If the authentication is successful, it will be run in the specific action.} else {this. handleUnauthorizedRequest (actionContext); // call failed for authentication }}/// <summary> // error returned /// </Summary> /// <param name = "actionContext"> </param> protected override void HandleUnauthorizedRequest (HttpActionContext actionContext) {JsonData jsonData = new JsonData (); jsonData. state = "400"; jsonData. message = "dear! You have not logged on to "; actionContext. response = new HttpResponseMessage (HttpStatusCode. OK) {Content = new StringContent (JsonHelper. objectToJSON (jsonData), Encoding. UTF8, "application/json ")};}}View Code
The UserModel is used to transmit data to specific actions.
Use HttpContext. Current. User = new UserModel () {loginUser = new_user}; // set the Current login Model
public class UserModel : IPrincipal { public er_wx_user loginUser { get; set; } public bool IsInRole(string name) { return true; } public IIdentity Identity { get; set; } }View Code
2. Model Authentication
Inheritance class for webApi model authentication: ActionFilterAttribute
The model authentication class is used on the Action
[ModelApprove] public HttpResponseMessage boundUserPhone([FromBody]boundUserPhone boundUserPhoneModel) { } View Code
Mainly rewrite two methods
1. When the OnActionExecuting model is used for authentication, the webApi is automatically called. If the model is used to receive data, it is automatically authenticated.
2. error responses for failed ErrorRequest Authentication
/// <Summary> /// Model Field authentication author KAI /// </summary> public class ModelApprove: actionFilterAttribute {// <summary> // model authentication /// </summary> /// <param name = "actionContext"> </param> public override void OnActionExecuting (httpActionContext actionContext) {// model authentication fails. // actionContext. modelState. whether IsValid model authentication passes automatic if (! ActionContext. modelState. isValid) {this. errorRequest (actionContext );}} /// <summary> // returned error // </summary> // <param name = "actionContext"> </param> protected void ErrorRequest (HttpActionContext actionContext) {// retrieve all error model authentication error content in this List <string> errorList = new List <string> (); foreach (var value in actionContext. modelState. values) {foreach (var error in value. errors) {errorList. add (error. errorMessage) ;}}// the following error response is written as JsonData jsonData = new JsonData (); jsonData. state = "300"; jsonData. message = errorList. firstOrDefault (); jsonData. backData. add ("info", errorList); actionContext. response = new HttpResponseMessage (HttpStatusCode. OK) {Content = new StringContent (JsonHelper. objectToJSON (jsonData), Encoding. UTF8, "application/json ")};}}View Code
3. Custom model authentication rules
Authentication rules are used on model attributes.
Public class addCardLog {[Required (ErrorMessage = "card ID cannot be blank")] public int card_id {get; set ;}}View Code
There are some built-in authentication rules
Namespace: using System. ComponentModel. DataAnnotations;
Public class addInfo {[Required (ErrorMessage = "content cannot be blank")] [StringLength (10, MinimumLength = 1, ErrorMessage = "length range 1-10")] [Range (typeof (string), "1", "2", ErrorMessage = "type: 1 or 2")] [RegularExpression (@ "^ 1 (3 | 4 | 5 | 7 | 8) \ d {9} $", ErrorMessage = "Regular Expression authentication error content")] [Compare ("name_two", ErrorMessage = "")] // check whether the content is the same as name_two. Do you need to enter public string name {get in the authentication password; set ;}public string name_two {get; set ;}}View Code
Custom rule Authentication
Custom rule inheritance class for webApi model authentication: ValidationAttribute
Mainly rewrite a method
1. IsValid
/// <Summary> // verification code check rules /// </summary> public class VerifyCodeCheck: ValidationAttribute {public string phoneString {get; set ;} /// <summary> /// check whether authentication is successful /// </summary> /// <param name = "value"> </param> /// <returns> </returns> protected override ValidationResult IsValid (object value, validationContext validationContext) {try {// value is the value of the authentication attribute // validationContext. objectInstance is the object of the current model. You can use reflection to obtain the value. // you may need to use another value to participate in the objectToMap method to convert the object into a key-Value Pair object var phone = CommonHelper. objectToMap (validationContext. objectInstance) [phoneString]. toString (); if (CacheHelper. get (phone ). toString (). equals (value. toString () {return ValidationResult. success;} return new ValidationResult (base. errorMessage);} catch {return new ValidationResult ("Verification Code invalid or incorrect ");}}}}View Code
Obtain the public attributes and values of the object through reflection.
/// <Summary> /// use reflection to Map object sets /// </summary> /// <typeparam name = "T"> </typeparam> /// <returns> </returns> public static Dictionary <string, object> objectToMap (object obj) {try {if (obj = null) throw new Exception (); Dictionary <string, object> map = new Dictionary <string, object> (); foreach (var attribute in obj. getType (). getProperties () // obtain the attribute list {map. add (attribute. name, attribute. getValue (obj) ;}return map ;}catch {return null ;}}View Code
Source code link: https://pan.baidu.com/s/1dEHWkut password: 29qr