Dar*_*ius 9 c# asp.net-mvc authorize-attribute asp.net-mvc-4 asp.net-web-api
我一直在互联网上试图找出为什么我的自定义AuthorizeAttribute在我的MVC WebApi中不起作用.我见过人们在SO上询问这类事情但是没有什么能帮助我解决我的问题:
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false,
Inherited = false)]
public sealed class CustomAuthorization : AuthorizeAttribute
{
//...
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
// custom auth logic, returns true if authorized, false otherwise
}
}
Run Code Online (Sandbox Code Playgroud)
我正在延伸System.Web.Mvc
而不是System.Web.Http
.但是,我AuthorizeCore(HttpContextBase httpContext)
永远不会被召唤.
我的类中有一个构造函数,CustomAuthorization
它接受params string[]
一个特定操作所需的自定义权限的名称,例如:
[CustomAuthorization("Some Permission")]
[System.Web.Http.HttpGet]
public CustomResponse SomeAction()
{
//...
}
Run Code Online (Sandbox Code Playgroud)
我希望实现的是每当请求使用该[CustomAuthorization]
属性修饰的动作时都会触发我的授权代码.如果授权失败,我还希望能够返回更具描述性的auth失败消息.不只是:
{"Message":"Authorization has been denied for this request."}
Run Code Online (Sandbox Code Playgroud)
我相信这涉及到覆盖HandleUnauthorizedRequest
但是我如何才能提供我自己的JSON响应将序列化的对象?
总而言之,即使我用我的[CustomAuthorization]
属性修饰动作,框架也不会调用我的授权代码.它只是直接执行操作中的代码.
其次,如何实现未经授权的响应来序列化自定义JSON对象?
感谢您提前的帮助,非常感谢!
好的,我最终解决了它,这是如何:
public override void OnAuthorization(HttpActionContext actionContext) {
....
if (!authorized) {
actionContext.Response =
actionContext.Request.CreateResponse(
HttpStatusCode.Unauthorized,
new Dictionary<string, string> {
{ "hello", "world" }
}
);
}
Run Code Online (Sandbox Code Playgroud)
}
产生结果:
{"hello":"world"}
Run Code Online (Sandbox Code Playgroud)
Dictionary对象是任意的,它只是演示了一个类型将成功序列化到Response.
如果您未设置,actionContext.Response
那么请求将继续执行目标操作 - 即.它被视为已被此过滤器授权.
希望能帮助其他人处于这个位置.
归档时间: |
|
查看次数: |
5804 次 |
最近记录: |