0

我正在尝试遵循教程Securing Asp.net但是当我尝试输入这一行时

GlobalConfiguration.Configuration.Filters.Add(new System.Web.Http.AuthorizeAttribute());

它给了我一个以下错误

The best overloaded method match for 'System.Web.Http.Filters.HttpFilterCollection.Add(System.Web.Http.Filters.IFilters)' has some invalid agruments 

下面是我的 Global.asax 代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using DatabaseService_WebAPI.App_Start;

namespace DatabaseService_WebAPI
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            System.Data.Entity.Database.SetInitializer(new DatabaseService_WebAPI.Models.ProductContextInitializer());
            System.Data.Entity.Database.SetInitializer(new DatabaseService_WebAPI.Models.LocalDBContextInitializer());
            System.Data.Entity.Database.SetInitializer(new DatabaseService_WebAPI.Models.GCMClassContextInitializer());
            System.Data.Entity.Database.SetInitializer(new DatabaseService_WebAPI.Models.ProductTypeContextInitializer());

            GlobalConfiguration.Configuration.Filters.Add(new System.Web.Mvc.AuthorizeAttribute());

            WebApiConfig.Configure(GlobalConfiguration.Configuration);

            AreaRegistration.RegisterAllAreas();

            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }

        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
            filters.Add(new System.Web.Mvc.AuthorizeAttribute());
            filters.Add(new RequireHttpsAttribute());
        }
    }
}

我不是 mvc 的专家开发人员。所以任何人都可以告诉如何添加过滤器?

4

1 回答 1

0

在 global.asax.cs 中创建此方法:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
   // add filters here
   filters.Add(new MyCustomFilter());
}

然后从Application_Start方法中调用它:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
}
于 2012-12-02T17:42:16.950 回答