Invalid Arguments error in Global.asax in mvc

2019-08-21 07:15发布

问题:

I`m trying to follow the tutorial Securing Asp.net but when i try to put this line

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

it gives me a following error

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

below is my Global.asax code

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());
        }
    }
}

I`m not an expert developer in mvc. so anyone can tell how to add filters?

回答1:

Create this method in global.asax.cs:

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

Then call it from the Application_Start method:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
}