我在 asp.net web api 上使用自定义授权。我按照以下链接 http://www.codeproject.com/Tips/376810/ASP-NET-WEB-API-Custom-Authorize-and-Exception-Han I像这样在我的控制器中使用属性名称
[我的自定义属性]
公共类用户控制器:apicontroller {
}
但它总是显示 401 未经授权的异常,尽管身份验证状态被授权。我已经完全按照它在创建自定义授权属性的链接中。
我的自定义授权类
public class tokenAuthorize : AuthorizeAttribute
{
DBEntity _objScrumDBEntities = new DBEntity ();
public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
{
base.OnAuthorization(actionContext);
if (actionContext.Request.Headers.GetValues("authenticationToken") != null)
{
// get value from header
string authenticationTokenValue = Convert.ToString(actionContext.Request.Headers.GetValues("authenticationToken").FirstOrDefault());
ObjectParameter m_tokenParam = new ObjectParameter("status", typeof(string));
_objScrumDBEntities.validateToken(authenticationTokenValue, m_tokenParam);
string status = Convert.IsDBNull(m_tokenParam.Value) ? null : (string)m_tokenParam.Value;
if (status == "false")
{
HttpContext.Current.Response.AddHeader("authenticationToken", authenticationTokenValue);
HttpContext.Current.Response.AddHeader("AuthenticationStatus", "NotAuthorized");
// actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden);
return;
}
else
{
HttpContext.Current.Response.AddHeader("authenticationToken", authenticationTokenValue);
HttpContext.Current.Response.AddHeader("AuthenticationStatus", "Authorized");
return;
}
//return;
}
//actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.ExpectationFailed);
//else
// actionContext.Response.ReasonPhrase = "Please provide valid inputs";
}
}
和我的控制器
[tokenAuthorize]
public class myController : ApiController
{
public IEnumerable<organization> Get()
{
return _objOrgRepository.GetAll();
}