asp.net mvc - Why class attribute not work in WebAPI? -


i used default asp.net mvc4 web application template , visual studio create initializesimplemembershipattribute in filters directory , create account controller this:

[authorize] [initializesimplemembership] public class accountcontroller : controller { /* default actions login, logoff, register, ...*/ } 

and try make accountcontroller webapi, code is:

[authorize] [initializesimplemembership] public class apiaccountcontroller : apicontroller {     [system.web.http.acceptverbs("get", "post")]     [system.web.http.httpget]     [system.web.http.httppost]     [system.web.http.allowanonymous]     [system.web.mvc.validateantiforgerytoken]     public string login(string username, string password, bool rememberme)     {         if (websecurity.login(username, password, persistcookie: rememberme))         {             return "ok";         }          return "failed";     } } 

now, when call api, break in line:

if (websecurity.login(username, password, persistcookie: rememberme))

and said: you must call "websecurity.initializedatabaseconnection" method before call other method of "websecurity" class.

i ran in initializesimplemembershipattribute , webapi controller same controller.

why attribute not run in webapi?

the [initializesimplemembership]-attribute inherits system.web.mvc.actionfilterattribute

action filters web api need inherit system.web.http.filters.actionfilterattribute, filter not getting executed on web api controller.

there's 2 things can do:

  • either implement own filter, inheriting system.web.http.filters.actionfilterattribute
  • add following code global.asax

    private static simplemembershipinitializer _initializer; private static object _initializerlock = new object(); private static bool _isinitialized;  protected void application_start() {     // ensure asp.net simple membership initialized once per app start  lazyinitializer.ensureinitialized(ref _initializer, ref _isinitialized, ref _initializerlock);  } 

for work need move logic initializemembership separate class , make sure can access global.asax.


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -