webapi身份验证
public class HTTPBasicAuthorizeAttribute : System.Web.Http.AuthorizeAttribute { public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext) { try { //用户名 IEnumerable<string> account = actionContext.Request.Headers.GetValues("account"); List<string> accountlist = account.ToList(); //密码 //IEnumerable<string> password = actionContext.Request.Headers.GetValues("password"); //List<string> passwordlist = password.ToList(); //string username = Encoding.Default.GetString(Convert.FromBase64String(accountlist[0])); //string pwd = Encoding.Default.GetString(Convert.FromBase64String(passwordlist[0])); PetaPoco.Database db = new PetaPoco.Database("DefaultConnection"); int linkinfo = db.ExecuteScalar<int>(string.Format(@"select * from (select right(sys.fn_VarBinToHexStr(hashbytes('MD5',UserName+Password)),32) as userinfo from LinkInfo) as t where userinfo = '{0}'", accountlist[0])); //用户验证逻辑 if (linkinfo != null) { IsAuthorized(actionContext); } else { HandleUnauthorizedRequest(actionContext); } } catch (Exception) { HandleUnauthorizedRequest(actionContext); } } 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); } }