Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy CustomRoleManager Initializer not run in Web API?
    primarykey
    data
    text
    <p>I created custom membership and custom role provider follow exact same this link:</p> <p><strong>for custom membership:</strong></p> <p><a href="http://msdn.microsoft.com/en-us/library/6tc47t75%28v=vs.100%29.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/6tc47t75(v=vs.100).aspx</a></p> <p>more info:</p> <p><a href="http://msdn.microsoft.com/en-us/library/ms366730%28v=vs.100%29.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms366730(v=vs.100).aspx</a></p> <p><strong>for custom role provider:</strong></p> <p><a href="http://msdn.microsoft.com/en-us/library/317sza4k%28v=vs.100%29.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/317sza4k(v=vs.100).aspx</a></p> <p>more info:</p> <p><a href="http://msdn.microsoft.com/en-us/library/tksy7hd7%28v=vs.100%29.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/tksy7hd7(v=vs.100).aspx</a></p> <p>and i have a SimpleMembershipInitializer</p> <pre><code>using System; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Threading; using WebMatrix.WebData; using TestProject.Web.Models; using System.Web.Http.Controllers; using System.Web.Http.Filters; namespace TestProject.Web.Filters { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public sealed class InitializeSimpleMembershipAttribute : ActionFilterAttribute { private static SimpleMembershipInitializer _initializer; private static object _initializerLock = new object(); private static bool _isInitialized; public override void OnActionExecuting(HttpActionContext actionContext) { LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock); } private class SimpleMembershipInitializer { public SimpleMembershipInitializer() { Database.SetInitializer&lt;UsersContext&gt;(null); try { using (var context = new UsersContext()) { if (!context.Database.Exists()) { ((IObjectContextAdapter)context).ObjectContext.CreateDatabase(); } } WebSecurity.InitializeDatabaseConnection("TestProjectEntities", "Users", "UsrID","UsrLoginName", autoCreateTables: false); } catch (Exception ex) { throw ex; } } } } } </code></pre> <p>and i wrote a web api for login:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Security; using DotNetOpenAuth.AspNet; using Microsoft.Web.WebPages.OAuth; using WebMatrix.WebData; using TestProject.Web.Models; using TestProject.Web.Filters; using System.Configuration; namespace TestProject.Web.Controllers { [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"; } } } </code></pre> <p>and my web.config is:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;!-- For more information on how to configure your ASP.NET application, please visit http://go.microsoft.com/fwlink/?LinkId=169433 --&gt; &lt;configuration&gt; &lt;configSections&gt; &lt;!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --&gt; &lt;section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /&gt; &lt;/configSections&gt; &lt;connectionStrings&gt; &lt;!--&lt;add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-TestProject.Web-20130430091159;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-TestProject.Web-20130430091159.mdf" providerName="System.Data.SqlClient" /&gt;--&gt; &lt;add name="TestProjectEntities" connectionString="Data Source=.;Initial Catalog=TestProject;Integrated Security=True" providerName="System.Data.SqlClient"/&gt; &lt;/connectionStrings&gt; &lt;appSettings&gt; &lt;add key="webpages:Version" value="2.0.0.0" /&gt; &lt;add key="webpages:Enabled" value="false" /&gt; &lt;add key="PreserveLoginUrl" value="true" /&gt; &lt;add key="ClientValidationEnabled" value="true" /&gt; &lt;add key="UnobtrusiveJavaScriptEnabled" value="true" /&gt; &lt;add key="enableSimpleMembership" value="false"/&gt; &lt;/appSettings&gt; &lt;system.web&gt; &lt;compilation debug="true" targetFramework="4.5" /&gt; &lt;httpRuntime targetFramework="4.5" /&gt; &lt;authentication mode="Forms"&gt; &lt;forms protection="All" loginUrl="/" timeout="2880" requireSSL="false" slidingExpiration="true" cookieless="UseCookies"&gt; &lt;credentials passwordFormat="SHA1" /&gt; &lt;/forms&gt; &lt;/authentication&gt; &lt;authorization&gt; &lt;!--&lt;deny users="?" lockAllAttributesExcept="AllowAnonymous" /&gt;--&gt; &lt;allow users="*"/&gt; &lt;/authorization&gt; &lt;machineKey validationKey="C50B3C89CB21F4F1422FF158A5B42D0E8DB8CB5CDA1742572A487D9401E3400267682B202B746511891C1BAF47F8D25C07F6C39A104696DB51F17C529AD3CABE" decryptionKey="8A9BE8FD67AF6979E7D20198CFEA50DD3D3799C77AF2B72F" validation="SHA1" /&gt; &lt;membership defaultProvider="UsersMembershipProvider" userIsOnlineTimeWindow="15"&gt; &lt;providers&gt; &lt;clear /&gt; &lt;add name="UsersMembershipProvider" type="TestProject.Web.Utility.UsersMembershipProvider" connectionStringName="TestProjectEntities" applicationName="TestProject" enablePasswordRetrieval="true" enablePasswordReset="true" requiresQuestionAndAnswer="true" requiresUniqueEmail="true" passwordFormat="Hashed" /&gt; &lt;/providers&gt; &lt;/membership&gt; &lt;roleManager defaultProvider="UsersRoleProvider" enabled="true" cacheRolesInCookie="true" cookieName=".ASPROLES" cookieTimeout="30" cookiePath="/" cookieRequireSSL="false" cookieSlidingExpiration="true" cookieProtection="All" &gt; &lt;providers&gt; &lt;clear /&gt; &lt;add name="UsersRoleProvider" type="TestProject.Web.Utility.UsersRoleProvider" connectionStringName="TestProjectEntities" applicationName="TestProject" writeExceptionsToEventLog="false" /&gt; &lt;/providers&gt; &lt;/roleManager&gt; &lt;pages&gt; &lt;namespaces&gt; &lt;add namespace="System.Web.Helpers" /&gt; &lt;add namespace="System.Web.Mvc" /&gt; &lt;add namespace="System.Web.Mvc.Ajax" /&gt; &lt;add namespace="System.Web.Mvc.Html" /&gt; &lt;add namespace="System.Web.Optimization" /&gt; &lt;add namespace="System.Web.Routing" /&gt; &lt;add namespace="System.Web.WebPages" /&gt; &lt;/namespaces&gt; &lt;/pages&gt; &lt;/system.web&gt; &lt;system.webServer&gt; &lt;validation validateIntegratedModeConfiguration="false" /&gt; &lt;handlers&gt; &lt;remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" /&gt; &lt;remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" /&gt; &lt;remove name="ExtensionlessUrlHandler-Integrated-4.0" /&gt; &lt;add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" /&gt; &lt;add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" /&gt; &lt;add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /&gt; &lt;/handlers&gt; &lt;/system.webServer&gt; &lt;runtime&gt; &lt;assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" /&gt; &lt;bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" /&gt; &lt;/dependentAssembly&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" /&gt; &lt;bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" /&gt; &lt;/dependentAssembly&gt; &lt;dependentAssembly&gt; &lt;assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" /&gt; &lt;bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" /&gt; &lt;/dependentAssembly&gt; &lt;/assemblyBinding&gt; &lt;/runtime&gt; &lt;entityFramework&gt; &lt;defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlCeConnectionFactory, EntityFramework"&gt; &lt;parameters&gt; &lt;parameter value="System.Data.SqlServerCe.4.0" /&gt; &lt;/parameters&gt; &lt;/defaultConnectionFactory&gt; &lt;!--&lt;defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework"&gt; &lt;parameters&gt; &lt;parameter value="v11.0" /&gt; &lt;/parameters&gt; &lt;/defaultConnectionFactory&gt;--&gt; &lt;/entityFramework&gt; &lt;/configuration&gt; </code></pre> <p>after run api with this link:</p> <blockquote> <p>/api/APIAccount/Login/?UserName=test1&amp;Password=123456&amp;RememberMe=true</p> </blockquote> <p>its give me error:</p> <pre><code>&lt;Error&gt; &lt;Message&gt;An error has occurred.&lt;/Message&gt; &lt;ExceptionMessage&gt; To call this method, the "Membership.Provider" property must be an instance of "ExtendedMembershipProvider". &lt;/ExceptionMessage&gt; &lt;ExceptionType&gt;System.InvalidOperationException&lt;/ExceptionType&gt; &lt;StackTrace&gt; at WebMatrix.WebData.WebSecurity.VerifyProvider() at WebMatrix.WebData.WebSecurity.Login(String userName, String password, Boolean persistCookie) at TestProject.Web.Controllers.APIAccountController.Login(String UserName, String Password, Boolean RememberMe) in c:\Visual Studio 2012\Projects\TestProject\TestProject.Web\Controllers\APIAccountController.cs:line 30 at lambda_method(Closure , Object , Object[] ) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.&lt;&gt;c__DisplayClass13.&lt;GetExecutor&gt;b__c(Object instance, Object[] methodParameters) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.&lt;&gt;c__DisplayClass5.&lt;ExecuteAsync&gt;b__4() at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1 func, CancellationToken cancellationToken) &lt;/StackTrace&gt; &lt;/Error&gt; </code></pre> <p><strong>I check it and see that CustomRoleManager Initializer not run in Web API and when i use view and not web api, its ok.</strong></p> <p><em><strong>What should i do?</em></strong></p> <p>I uploaded test project in <a href="http://filebin.net/k8cqbyltac" rel="nofollow">http://filebin.net/k8cqbyltac</a> and it made by VS 2012, C#, MVC4, .Net 4.5</p> <p>plaese check this URL after run for seeing error:</p> <blockquote> <p>/api/APIAccount/Login/?UserName=test1&amp;Password=123456&amp;RememberMe=true</p> </blockquote>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload