ASP.NET Web API 覆盖处理程序的授权过滤器
ASP.NET Web API Override authorization filter for a handler
如何在 Web API 中禁用特定 GET 处理程序的授权过滤器?
class 级别有一个自定义授权过滤器,但对于其中一种方法,我需要没有安全性。我尝试应用 [AllowAnonymous]
属性,但它仍然通过更高级别的过滤器运行并失败。该自定义过滤器源自 AuthorizationFilterAttribute
。 class 还有另外两个属性:OverrideAuthentication
和 EnableCors
。
我尝试了 AllowAnonymous
属性,但没有。
示例代码:
[EnableCors(origins: "*", headers: "*", methods: "*")]
[OverrideAuthentication]
[AccountAuthorization]
public class AccountsController : ApiController
{
[Route("api/accounts/{accountNumber}/GetX")]
[AllowAnonymous]
[HttpGet]
public HttpResponseMessage GetX(string accountNumber)
{
HttpResponseMessage response = null;
IEnumerable<string> apiKey;
if (!Request.Headers.TryGetValues("X-ApiKey", out apiKey) || apiKey.Count() != 1 || apiKey.First() != API_KEY)
{
throw new HttpResponseException(HttpStatusCode.Forbidden);
}
// Process
// ..
// ..
return response;
}
}
编辑:链接的答案没有解释解决方案。
终于想通了
由于 class/controller 级别上已经存在自定义授权过滤器,因此,要覆盖特定的操作处理程序(方法)并使其在没有任何授权过滤器的情况下工作,我们需要覆盖过滤器在 controller/class 级别。所以添加 OverrideAuthorization
过滤器就可以了。现在 AllowAnonymous
将发挥它的魔力。
[Route("api/accounts/{accountNumber}/GetX")]
[AllowAnonymous]
[OverrideAuthorization]
[HttpGet]
public HttpResponseMessage GetX(string accountNumber)
{
// Process
// ..
// ..
}
如何在 Web API 中禁用特定 GET 处理程序的授权过滤器?
class 级别有一个自定义授权过滤器,但对于其中一种方法,我需要没有安全性。我尝试应用 [AllowAnonymous]
属性,但它仍然通过更高级别的过滤器运行并失败。该自定义过滤器源自 AuthorizationFilterAttribute
。 class 还有另外两个属性:OverrideAuthentication
和 EnableCors
。
我尝试了 AllowAnonymous
属性,但没有。
示例代码:
[EnableCors(origins: "*", headers: "*", methods: "*")]
[OverrideAuthentication]
[AccountAuthorization]
public class AccountsController : ApiController
{
[Route("api/accounts/{accountNumber}/GetX")]
[AllowAnonymous]
[HttpGet]
public HttpResponseMessage GetX(string accountNumber)
{
HttpResponseMessage response = null;
IEnumerable<string> apiKey;
if (!Request.Headers.TryGetValues("X-ApiKey", out apiKey) || apiKey.Count() != 1 || apiKey.First() != API_KEY)
{
throw new HttpResponseException(HttpStatusCode.Forbidden);
}
// Process
// ..
// ..
return response;
}
}
编辑:链接的答案没有解释解决方案。
终于想通了
由于 class/controller 级别上已经存在自定义授权过滤器,因此,要覆盖特定的操作处理程序(方法)并使其在没有任何授权过滤器的情况下工作,我们需要覆盖过滤器在 controller/class 级别。所以添加 OverrideAuthorization
过滤器就可以了。现在 AllowAnonymous
将发挥它的魔力。
[Route("api/accounts/{accountNumber}/GetX")]
[AllowAnonymous]
[OverrideAuthorization]
[HttpGet]
public HttpResponseMessage GetX(string accountNumber)
{
// Process
// ..
// ..
}