【发布时间】:2020-10-15 23:23:34
【问题描述】:
需要使用 IAntiforgery 进行 csrf 保护。只是试图注入服务。这样做时,我收到“尝试激活 'APi.Startup' 时无法解析类型 'Microsoft.AspNetCore.Antiforgery.IAntiforgery' 的服务”。错误。我在这里发布代码。希望社区能够在这里为我提供帮助。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using APi.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace APi
{
public class Startup
{
IAntiforgery _antiforgery;
public Startup(IConfiguration configuration,IAntiforgery antiforgery)
{
Configuration = configuration;
_antiforgery = antiforgery;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddTransient<IAntiforgery>();
services.AddDbContext<EmployeeContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("SQLServerConnection")));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
【问题讨论】:
-
IAntiforgery直到ConfigureServices()被调用后才能从 DI 获得,因此构造函数无法使用。只有IHostingEnvironment和IConfiguration可以注入到构造函数中。 -
@MartinCostello 感谢您的回复。我不知道。因此,如果我要在使用 IAntiforgery 的 Configure 方法中制作中间件,我该怎么做?
-
你可以在你的中间件的方法上设置
IAntiforgery一个方法来处理请求,或者从HttpContext.RequestServices属性中解析它。
标签: c# asp.net-core antiforgerytoken