简体   繁体   English

MVC Controller,动作过滤器不工作

[英]MVC Controller, Action Filters not working

I want to add Bearer Authentication for the Controllers but it is not running the code from the Action Filter.我想为控制器添加承载身份验证,但它没有运行动作过滤器中的代码。 I tried to add Debug.WriteLine(...);我试图添加Debug.WriteLine(...); but it dont show anything in the output.但它在 output 中没有显示任何内容。

fetch:拿来:

fetch('api/Test/Select', {
   headers: {
      'Content-type': 'application/json',
      'Authorization': `Bearer ${sessionStorage.getItem("token")}`,
   },
   method: 'GET',
})

and the MVC Controller:和 MVC Controller:

using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Hosting;

namespace API
{
    [BearerAuthentication] //<-- Action Filter
    [Route("api/Test")]
    public class TestController : ControllerBase
    {
        //...

       [HttpGet("Select")]
       public IActionResult Select()
       {
           try
           {
              return Ok(FirstService.Select());
           }
           catch (Exception ex)
           {
              return Conflict(ex);
           }
       }
//...
        

Action Filter:动作过滤器:

    public class BearerAuthenticationAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext context)
        {
            Debug.WriteLine("Why are u not working?"); //<-- Debug Console shows nothing

            HttpRequestMessage request = context.Request;
            AuthenticationHeaderValue authorization = request.Headers.Authorization;

            //...
        }
    }

The issue that your BearerAuthenticationAttribute class extends the ActionFilterAttribute class but does not implement the IActionFilter interface.您的BearerAuthenticationAttribute class 扩展ActionFilterAttribute class 但未实现IActionFilter接口的问题。 Your class must explicitly implement the IActionFilter interface for the OnActionExecuting method to fire.您的 class 必须显式实现IActionFilter接口才能触发OnActionExecuting方法。

Here is an example of the implementation from a Microsoft Hands On Lab :以下是Microsoft Hands On Lab的实施示例:

public class CustomActionFilter : ActionFilterAttribute, IActionFilter
{
    void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
    {
        // TODO: Add your action filter's tasks here

        // Log Action Filter call
        using (MusicStoreEntities storeDb = new MusicStoreEntities())
        {
            ActionLog log = new ActionLog()
            {
                Controller = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName,
                Action = string.Concat(filterContext.ActionDescriptor.ActionName, " (Logged By: Custom Action Filter)"),
                IP = filterContext.HttpContext.Request.UserHostAddress,
                DateTime = filterContext.HttpContext.Timestamp
            };
            storeDb.ActionLogs.Add(log);
            storeDb.SaveChanges();
            OnActionExecuting(filterContext);
        }
    }
}

If your authentication method is bearer, then you can just do [Authorize] and don't forget to use [ApiController] so .net knows it needs to verify each endpoint setup:如果您的身份验证方法是不记名,那么您只需执行[Authorize]并且不要忘记使用[ApiController]以便 .net 知道它需要验证每个端点设置:

using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Authorization;

namespace API
{
    [ApiController]
    [Authorize]
    [Route("api/Test")]
    public class TestController : ControllerBase
    {
        //...

       [HttpGet("Select")]
       public IActionResult Select()
       {
           try
           {
              return Ok(FirstService.Select());
           }
           catch (Exception ex)
           {
              return Conflict(ex);
           }
       }
//...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM