首页 新闻 赞助 找找看

.net core 2.0 下重写Authorize没有生效的问题

0
悬赏园豆:5 [待解决问题]

重写类

引用,但都没有命中断点

jobroon的主页 jobroon | 初学一级 | 园豆:157
提问于:2019-08-21 19:24
< >
分享
所有回答(3)
0
dudu | 园豆:31075 (高人七级) | 2019-08-21 21:33
0

你请求的url呢.

吴瑞祥 | 园豆:29449 (高人七级) | 2019-08-22 22:00

自动生成的, api/Authorize/AuthorizeTest

支持(0) 反对(0) jobroon | 园豆:157 (初学一级) | 2019-08-29 12:36
0

按照你的代码路子,我改成如下:

// 重写类
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace iTOP.Web.CustomAttribute
{
    /// <summary>
    /// 重写实现处理授权失败时返回json,避免跳转登录页
    /// </summary>
    public class ApiTestAuthorize : AuthorizeAttribute, IAuthorizationFilter
    {
        public ApiTestAuthorize()
        {
        }

        public void OnAuthorization(AuthorizationFilterContext context)
        {
            var user = context.HttpContext.User;

            if (!user.Identity.IsAuthenticated)
            {
                context.Result = new JsonResult(value: new
                {
                    success = false,
                    errs = new[] { "服务端拒绝访问:你没有权限,或者掉线了" }
                }) ;
            }
        }
    }
}
// 控制器
using iTOP.Web.CustomAttribute;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

namespace iTOP.Web.Controllers
{
    [Produces("application/json")]
    [Route("api/Authorize")]
    [ApiTestAuthorize]
    public class AuthorizeController : Controller
    {
        /// <summary>
        /// 授权方法
        /// </summary>
        /// <returns></returns>
        [HttpGet("[action]")]
        public async Task<IActionResult> AuthorizeTest()
        {
            var json = new JsonResult(value: new
            {
                code ="200",
                data = new { },
                message =  $"AuthorzieTest",
                remark = string.Empty
            });

            return await Task.FromResult(json);
        }
    }
}

看看访问的接口, 为了方便测试,我用的 GET

taadis | 园豆:211 (菜鸟二级) | 2019-08-31 10:08
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册