我的 API 中有一個過濾器(用于 Auth),但是為了檢查令牌,我必須查看我的資料庫,這并不難,但是當我想通過我的 ctor 獲取我的 DataBaseContext 時,我不能再使用過濾器了. 看這里:
這是過濾器類的一部分:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class ApiAuth : Attribute, IAsyncActionFilter
{
private readonly DataBaseContext _db;
public ApiAuth(DataBaseContext db)
=> _db = db;
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
}
這是用戶控制器的一部分
[Route("api/v1/[controller]")]
[ApiController]
[ApiAuth]
public class UserController : Controller
{
}
“[ApiAuth]”現在給我一個錯誤,它需要一個 DataBaseContext,它不能給它。
錯誤“CS7036:沒有給出與“ApiAuth.ApiAuth(Databasecontext)”的形式引數“db”匹配的引數。”
我的問題是,我不知道如何獲得我的背景關系,你只能通過ctor來獲得它,還是我錯了?
uj5u.com熱心網友回復:
有幾件事要在這里檢查。
- 您是否在啟動類的方法中注冊了dbcontext
ConfigureServices?
像這樣
services.AddDbContext<YourDBContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
- 您是否在全域/或作為 IoC 容器中的服務注冊了過濾器
ConfigureServices?
使用此設定,您應該在過濾器中獲得 dbcontext。
否則,您可以使用服務定位器模式來決議不需要建構式注入的 dbcontext。
var context = context.HttpContext.RequestServices.GetService<DataBaseContext>();
你的過濾器也應該像這樣應用
[ServiceFilter(typeof(ApiAuth))]
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/463361.html
上一篇:如何在oracle中使用trunc(sysdate)獲取以前的作業日期
下一篇:按位運算和箭頭函式回傳陳述句
