最近在做Web api接口,因为之前没做过也没用过,所以前期遇到了很多问题,尤其是授权这块,因此写下这篇文档记录一下。
好了不多说,直接开始
首先要先
继承using System.Web.Http
webapi授权的时候要重写AuthorizeAttribute里的OnAuthorization方法
[AttributeUsageAttribute(AttributeTargets.Class | AttributeTargets.Method, Inherited = true,
AllowMultiple = true)]
public class MyTestAppAttribute : AuthorizeAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
if(true)
{
//接下来的操作
}
else
{
actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
}
}
}
接下来在
[MyTestApp]
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
有一点一定要注意,对于ApiController 授权的时候
里面的AuthorizeAttribute是属于using System.Web.Http命名空间下的
而Controller的授权是AuthorizeAttribute类是在using System.Web.Mvc下的
并且重写的方法也不一样
Controller里要重写的是AuthorizeCore方法
ApiController 里面重写的是OnAuthorization方法
好了就到这里吧