在 .Net Framework 4.7 应用程序中使用 .Net Standard 库

Vah*_*ian 1 .net c# .net-core asp-net-mvc-1 .net-standard-2.0

我有一组使用 .Net Standard 2.0 开发的类库。这些类库之一实现了IAuthorizationFilter位于Microsoft.AspNetCore.Mvc.Filters命名空间中的接口。

public class AuthorizationFilter : IAuthorizationFilter
{
    public AuthorizationFilter() {}

    public void OnAuthorization(AuthorizationFilterContext context)
    {/*Code cropped for the case of simplicity*/}
}
Run Code Online (Sandbox Code Playgroud)

另一个类库的主要职责是注册依赖注入配置。

   public static class ServiceCollectionExtensions
    {
        public static IServiceCollection MyCustomConfigure(this IServiceCollection services)
        {
            //...Code cropped for the case of simplicity
            services.AddMvc(config => { config.Filters.Add(typeof(AuthorizationFilter)); });
            return services;
        }
}
Run Code Online (Sandbox Code Playgroud)

除了这些 .Net Standard 类库之外,我还有一个使用ASP.Net MVC(.Net Framework 4.7)开发的 Web 应用程序项目

我在这里有两个主要问题:

  1. 我需要添加我的FilterAttribute类来ASP.Net MVC's过滤列表,它会抛出一个异常说:

给定的过滤器实例必须实现以下一个或多个过滤器接口:System.Web.Mvc.IAuthorizationFilter、System.Web.Mvc.IActionFilter、System.Web.Mvc.IResultFilter、System.Web.Mvc.IExceptionFilter、System.Web .Mvc.Filters.IAuthenticationFilter。

我在我的 ASP.Net MVC 应用程序中以这种方式注册了过滤器:

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        //...Code cropped for the case of simplicity
        filters.Add(typeof(AuthorizationFilter));
    }
}
Run Code Online (Sandbox Code Playgroud)

显然我不想System.Web在我的 .Net Standard 类库中添加引用,另一方面,我不知道如何解决这个问题!

  1. 第二个问题,是我可以调用我的services.MyCustomConfigure()方法的地方。在 .Net Core 应用程序中,我ConfigureServicesStartup类的方法中调用了这个方法,但我不知道如何调用它ASP.Net MVC

    public class Startup
    {
        //...Code cropped for the case of simplicity
        public void ConfigureServices(IServiceCollection services)
        {
            services.MyCustomConfigure()
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)

Mar*_*ich 5

ASP.NET(WebForms、MVC、WebAPI)和 ASP.NET Core 是不同的框架,虽然它们共享相似的概念(如过滤器属性),但它们是不同的,您不能使用为 ASP.NET Core 编写的组件(使用其 API ( Microsoft.AspNetCore.*)经典的 ASP.NET。

这意味着您需要为 ASP.NET Core 和 ASP.NET MVC 5 提供不同的实现。