标签:自己 ret options command span gen efault box serial
在WEBAPI中,AuthorizeAttribute类重写时,如何获取post数据是个难题,网上找资料也不好使,只能自己研究,通过研究发现,WEBAPI给了我们获取POST数据的可能,下面介绍一下:
//将POST数据以字符串的形式读取,例如post的json数据,就可以以这种方式读取
actionContext.Request.Content.ReadAsStringAsync();
//将POST数据以内容流的形式读取
actionContext.Request.Content.ReadAsStreamAsync();
//将POST数据以FORM键值对的形式读取,但是提交的数据须得是FORM提交的才可以
actionContext.Request.Content.ReadAsFormDataAsync();
代码具体如下:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Net.Http; 5 using System.Web; 6 using System.Web.Http; 7 using System.Web.Http.Controllers; 8 using BoxSecurity; 9 10 namespace BoxWebApiFilter 11 { 12 [AttributeUsage(AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] 13 public class ApiAuthorizeFilter : AuthorizeAttribute 14 { 15 private static List<string> PublicCmds = new List<string>() 16 { 17 "XXXX" 18 }; 19 protected override bool IsAuthorized(HttpActionContext actionContext) 20 { 21 // 验证token 22 //var token = actionContext.Request.Headers.Authorization; 23 var ts = actionContext.Request.Headers.Where(c => c.Key.ToLower() == "tokenxxx").FirstOrDefault().Value; 24 var requestContent = actionContext.Request.Content.ReadAsStringAsync();//读取post提交的json数据 25 requestContent.Wait();//等待异步读取结束 26 var inputJson = requestContent.Result; 27 //此接口无需token验证 28 BoxCommand.CmdRequest request = 29 Newtonsoft.Json.JsonConvert.DeserializeObject<BoxCommand.CmdRequest>(inputJson); 30 if (PublicCmds.Contains(request.Cmd)) 31 { 32 return true; 33 } 34 35 if (ts != null && ts.Count() > 0) 36 { 37 var token = ts.First<string>(); 38 // 验证token 39 return TokenHelper.IsExistToken(token); 40 } 41 42 if (actionContext.Request.Method == HttpMethod.Options) 43 return true; 44 return false; 45 46 } 47 } 48 }
WebAPI的AuthorizeAttribute扩展类中获取POST提交的数据
标签:自己 ret options command span gen efault box serial
原文地址:https://www.cnblogs.com/zhifengfly/p/9272829.html