你请求的url呢.
自动生成的, api/Authorize/AuthorizeTest
按照你的代码路子,我改成如下:
// 重写类
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