I can not upload large files. My page is base in ASP.NET.
In IIS I have 2 sites;
-1 for web service
-1 for web page
I try many ways that I found, but no work
Web service config;
////////////////////////////
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appSettings>
...
</appSettings>
<connectionStrings>
...
</connectionStrings>
<system.web>
<httpRuntime maxRequestLength="50097151" />
<compilation debug="true" targetFramework="4.5.2" />
<authentication mode="Windows" />
<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID" />
</system.web>
</configuration>
////////////////////////////
////////////////////////////
Web page config;
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath=".\....exe" arguments="" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="true">
<environmentVariables />
</aspNetCore>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="50741824" />
</requestFiltering>
</security>
</system.webServer>
</configuration>
I expect upload large files, but the actual is that I only can upload small files.
[HttpPost]
[DisableRequestSizeLimit]
public ActionResult uplo(string filename, string base64)
{
if (base64 != null && filename != null)
{
Models.filemodel archmod = new Models.filemodel ();
var xxx= archmod .namefunction(filename, base64);
return new EmptyResult();
}
return new EmptyResult();
}
It works with [DisableRequestSizeLimit] tag !!!
Related
I have App.config file in C# application.
I want to partially replace all Keys matching ".UAT" with ".PROD" using xdt tranform.
<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<appSettings>
<add key="MyParam1.UAT" value="param1"/>
<add key="MyParam2.UAT" value="param2"/>
<add key="MyParam2.UAT" value="param3"/>
</appSettings>
</configuration>
Here is the output I want
<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<appSettings>
<add key="MyParam1.PROD" value="param1"/>
<add key="MyParam2.PROD" value="param2"/>
<add key="MyParam2.PROD" value="param3"/>
</appSettings>
</configuration>
So far I've tried this using CustomTransform but it replaces only one element instead of all element. How can i get this to replace all elements
<?xml version="1.0"?>
<!-- For more information on using web.config transformation visit http://go.microsoft.com/fwlink/?LinkId=125889 -->
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<appSettings>
<add xdt:Locator="Condition(contains(#key, '.UAT'))" xdt:Transform="AttributeRegexReplace(Attribute='key', Pattern='.UAT',Replacement='.PROD')" />
</appSettings>
</configuration>
I found the answer here where I had to replace the Apply method with this method that iterates over all attributes
protected override void Apply()
{
foreach (XmlNode target in this.TargetNodes)
{
foreach (XmlAttribute att in target.Attributes)
{
if (string.Compare(att.Name, this.AttributeName, StringComparison.InvariantCultureIgnoreCase) == 0)
{ // get current value, perform the Regex
att.Value = Regex.Replace(att.Value, this.Pattern, this.Replacement);
}
}
}
}
I have done research on enabling gzpi compression on GoDaddy shared windoes hosting and here is the proposed solution:
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true"/>
<httpCompression directory="%SystemDrive%\inetpub\temp\IIS Temporary Compressed Files">
<scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll"/>
<dynamicTypes>
<add mimeType="text/*" enabled="true"/>
<add mimeType="message/*" enabled="true"/>
<add mimeType="application/javascript" enabled="true"/>
<add mimeType="*/*" enabled="false"/>
</dynamicTypes>
<staticTypes>
<add mimeType="text/*" enabled="true"/>
<add mimeType="message/*" enabled="true"/>
<add mimeType="application/javascript" enabled="true"/>
<add mimeType="*/*" enabled="false"/>
</staticTypes>
</httpCompression>
<urlCompression doStaticCompression="true" doDynamicCompression="true"/>
</system.webServer>
But this is currently not working and I am not getting http response header, Content-Encoding gzip.
Can someone help me with this?
Thanks
Adding that to my Web.Config allowed my Godaddy site to compress aspx page responses. But to compress ASMX WebService responses, I had to additionally add this to Global.asax:
void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
var app = sender as HttpApplication;
var acceptEncoding = app.Request.Headers["Accept-Encoding"];
var prevUncompressedStream = app.Response.Filter;
if (!string.IsNullOrEmpty(acceptEncoding))
{
acceptEncoding = acceptEncoding.ToLower();
if (acceptEncoding.Contains("gzip"))
{
app.Response.Filter = new GZipStream(prevUncompressedStream, CompressionMode.Compress);
app.Response.AppendHeader("Content-Encoding", "gzip");
}
}
Response.Cache.VaryByHeaders["Accept-Encoding"] = true;
}
Problem Statement:
Performing MVC CRUD operations using WCF Service.Everything was working fine with SOAP,but when i changed from SOAP to REST it is giving end point error.I suspect that there might be some problem with my webconfig..!!!
Exception Details:
"There was no endpoint listening at http://localhost:8733/Design_Time_Addresses/ALCMS.MasterConfigurationService/Service1/InsertAssetType that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details."
WCF REST service is hosting properly and it is running.I'm getting the exception mentioned above in WCF REST Service method calls in controller like :
objSvcMasterConfig.InsertAssetType(objAssetTypeDC);
objSvcMasterConfig.UpdateAssetType(objAssetTypeDC);
objSvcMasterConfig.DeleteAssetType(objAssetTypeDC);
What i'm doing wrong??
I'm having two projects in Solution
WCF Service library
MVC Razor application
1. WCF Service Library:
IService1.cs
Data Contract:
[DataContract]
public class AssetTypeDC
{
[DataMember]
public int ID { get; set; }
[DataMember]
public int AssetTypeID { get; set; }
[DataMember]
public string Name { get; set; }
}
Service Contract:
[ServiceContract]
public interface IService1
{
#region Asset Type
[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "InsertAssetType")]
bool InsertAssetType(AssetTypeDC objAssetTypeDC);
[WebInvoke(Method = "PUT",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "UpdateAssetType")]
[OperationContract]
bool UpdateAssetType(AssetTypeDC objAssetTypeDC);
[WebInvoke(Method = "DELETE",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "DeleteAssetType")]
[OperationContract]
bool DeleteAssetType(AssetTypeDC objAssetTypeDC);
#endregion
}
Service.cs
public bool InsertAssetType(AssetTypeDC objAssetTypeDC)
{
try
{
objAssetType.ID = objAssetTypeDC.ID;
objAssetType.AssetTypeID = objAssetTypeDC.AssetTypeID;
objAssetType.Name = objAssetTypeDC.Name;
dbEntity.AssetTypes.Attach(objAssetType);
var entry = dbEntity.Entry(objAssetType);
dbEntity.AssetTypes.Add(objAssetType);
dbEntity.SaveChanges();
return true;
}
catch
{
return false;
}
}
public bool UpdateAssetType(AssetTypeDC objAssetTypeDC)
{
try
{
objAssetTypeID = ID;
objAssetType.AssetTypeID = objAssetTypeDC.AssetTypeID;
objAssetType.Name = objAssetTypeDC.Name;
dbEntity.AssetTypes.Attach(objAssetType);
var entry = dbEntity.Entry(objAssetType);
entry.Property(e => e.Name).IsModified = true;
dbEntity.SaveChanges();
return true;
}
catch
{
return false;
}
}
public bool DeleteAssetType(AssetTypeDC objAssetTypeDC)
{
try
{
objAssetType.AssetTypeID = objAssetTypeDC.AssetTypeID;
objAssetType.ID = objAssetTypeDC.ID;
dbEntity.AssetTypes.Attach(objAssetType);
dbEntity.Entry(objAssetType).State = EntityState.Deleted;
dbEntity.SaveChanges();
return true;
}
catch
{
return false;
}
}
App.Config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" />
</system.web>
<system.serviceModel>
<services>
<service name="ALCMS.MasterConfigurationService.Service1" behaviorConfiguration="ALCMS.MasterConfigurationService.Service1Behaviour">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8733/Design_Time_Addresses/ALCMS.MasterConfigurationService/Service1/" />
</baseAddresses>
</host>
<endpoint address="" binding="webHttpBinding" contract="ALCMS.MasterConfigurationService.IService1" behaviorConfiguration="ALCMS.MasterConfigurationService.RESTEndpointBehaviour">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="ALCMS.MasterConfigurationService.RESTEndpointBehaviour">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="ALCMS.MasterConfigurationService.Service1Behaviour">
<serviceMetadata httpGetEnabled="True" httpsGetEnabled="True" />
<serviceDebug includeExceptionDetailInFaults="False" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
<connectionStrings><add name="DB_V2Entities" connectionString="metadata=res://*/Entities.MasterConfigurationEntity.csdl|res://*/Entities.MasterConfigurationEntity.ssdl|res://*/Entities.MasterConfigurationEntity.msl;provider=System.Data.SqlClient;provider connection string="data source=SQL-PC\SQLEXPRESS;initial catalog=DB_V2;user id=sa;password=Sql#123;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" /></connectionStrings></configuration>
2.MVC Application
Controller:
Insert Operation:
[HttpPost]
public ActionResult Create(AssetTypeModel assettypemodel)
{
if (ModelState.IsValid)
{
objAssetTypeDC.ID = 1;
objAssetTypeDC.AssetTypeID = assettypemodel.ID;
objAssetTypeDC.Name = assettypemodel.Name;
objSvcMasterConfig.InsertAssetType(objAssetTypeDC);
return RedirectToAction("Index");
}
return View(assettypemodel);
}
Update Operation:
[HttpPost]
public ActionResult Edit(AssetTypeModel assettypemodel, int id, int ID)
{
if (ModelState.IsValid)
{
objAssetTypeDC.ID = assettypemodel.ID = ID;
objAssetTypeDC.AssetTypeID = assettypemodel.AssetTypeID = id;
objAssetTypeDC.Name = assettypemodel.Name;
objSvcMasterConfig.UpdateAssetType(objAssetTypeDC);
return RedirectToAction("Index");
}
return View(assettypemodel);
}
Delete Operation:
public ActionResult Delete(int id = 0, int ID = 0)
{
AssetTypeModel assettypemodel = db.AssetType.Find(id, ID);
if (assettypemodel == null)
{
return HttpNotFound();
}
return View(assettypemodel);
}
Web.Config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="DB" connectionString="Data Source=SQL-PC\SQLEXPRESS;initial catalog=DB_V2;Persist Security Info=True;User ID=sa;Password=Sql#123;Pooling=False;" providerName="System.Data.SqlClient" />
<add name="DBEntities" connectionString="metadata=res://*/Entities.WebEntity.csdl|res://*/Entities.WebEntity.ssdl|res://*/Entities.WebEntity.msl;provider=System.Data.SqlClient;provider connection string="data source=SQL\SQLEXPRESS;initial catalog=DB_V2;user id=sa;Password=Sql#123;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" /></connectionStrings>
<appSettings>
<add key="webpages:Version" value="2.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="PreserveLoginUrl" value="true" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5"><assemblies><add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /></assemblies></compilation>
<httpRuntime targetFramework="4.5" />
<authentication mode="Forms">
<forms loginUrl="~/Login" protection="All" timeout="2880" />
</authentication>
<sessionState mode="InProc" timeout="30" stateConnectionString="tcpip=SQL-PC\SQLEXPRESS,1433" cookieless="false" regenerateExpiredSessionId="false" />
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Optimization" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
</namespaces>
</pages>
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<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" />
<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" />
<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" />
</handlers>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="WebHttpBinding_IService1" />
</webHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="ALCMS.MasterConfigurationService.RESTEndpointBehaviour">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<client>
<endpoint address="http://localhost:8733/Design_Time_Addresses/ALCMS.MasterConfigurationService/Service1/" binding="webHttpBinding" bindingConfiguration="WebHttpBinding_IService1" behaviorConfiguration="ALCMS.MasterConfigurationService.RESTEndpointBehaviour" contract="MasterConfigurationServiceReference.IService1" name="WebHttpBinding_IService1" />
</client>
</system.serviceModel>
</configuration>
Mr Vishal,
Instead of converting, you can develop in REST only.
ELMAH for MVC support following appsettings configurations
elmah.mvc.allowedRoles
elmah.mvc.allowedUsers
to secure the elmah route path using roles/users. Apparently, it works fine for windows or forms authentications. But I couldn't make it working for the claim based authentication.
Does anyone have experience with this?
I do this in web config
<elmah>
<security allowRemoteAccess="true" />
<errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="elmah-sqlserver" applicationName="Eers.Web"/>
</elmah>
and further down
<location path="elmah">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
<location path="elmah.axd" inheritInChildApplications="false">
<system.web>
<httpHandlers>
<add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" />
</httpHandlers>
</system.web>
<system.webServer>
<handlers>
<add name="ELMAH" verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" preCondition="integratedMode" />
</handlers>
</system.webServer>
</location>
If you take note of the node it works just like any other security in MVC. It does not work with Claims though. for that You will have to write an Action filter
<authorization>
<allow users="*"/>
</authorization>
Here is my Actionfilter
public class ElmahRequestAuthorizationFilter : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext.IsChildAction) return;
var controller = filterContext.RouteData.Values["controller"] as string;
if (controller != null && controller.ToLowerInvariant() != "elmah") return;
var authenticationComponent = GetAuthenticationInfo() // A method that will return us roles;
var goodRoles = new List<string> {
"TestRole",
"ThirdLevelSupport",
"Administrator"
};
var roles = authenticationComponent.Roles ?? new List<string>();
var thouShaltPass = roles.Intersect(goodRoles).Any();
if (!thouShaltPass)
{
throw new HttpException(404, "Not Found");
}
}
}
I created custom membership and custom role provider follow exact same this link:
for custom membership:
http://msdn.microsoft.com/en-us/library/6tc47t75(v=vs.100).aspx
more info:
http://msdn.microsoft.com/en-us/library/ms366730(v=vs.100).aspx
for custom role provider:
http://msdn.microsoft.com/en-us/library/317sza4k(v=vs.100).aspx
more info:
http://msdn.microsoft.com/en-us/library/tksy7hd7(v=vs.100).aspx
and i have a SimpleMembershipInitializer
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<UsersContext>(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;
}
}
}
}
}
and i wrote a web api for login:
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";
}
}
}
and my web.config is:
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<!--<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" />-->
<add name="TestProjectEntities" connectionString="Data Source=.;Initial Catalog=TestProject;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="2.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="PreserveLoginUrl" value="true" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="enableSimpleMembership" value="false"/>
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<authentication mode="Forms">
<forms protection="All" loginUrl="/" timeout="2880" requireSSL="false" slidingExpiration="true" cookieless="UseCookies">
<credentials passwordFormat="SHA1" />
</forms>
</authentication>
<authorization>
<!--<deny users="?" lockAllAttributesExcept="AllowAnonymous" />-->
<allow users="*"/>
</authorization>
<machineKey validationKey="C50B3C89CB21F4F1422FF158A5B42D0E8DB8CB5CDA1742572A487D9401E3400267682B202B746511891C1BAF47F8D25C07F6C39A104696DB51F17C529AD3CABE"
decryptionKey="8A9BE8FD67AF6979E7D20198CFEA50DD3D3799C77AF2B72F"
validation="SHA1" />
<membership defaultProvider="UsersMembershipProvider" userIsOnlineTimeWindow="15">
<providers>
<clear />
<add
name="UsersMembershipProvider"
type="TestProject.Web.Utility.UsersMembershipProvider"
connectionStringName="TestProjectEntities"
applicationName="TestProject"
enablePasswordRetrieval="true"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
requiresUniqueEmail="true"
passwordFormat="Hashed" />
</providers>
</membership>
<roleManager defaultProvider="UsersRoleProvider"
enabled="true"
cacheRolesInCookie="true"
cookieName=".ASPROLES"
cookieTimeout="30"
cookiePath="/"
cookieRequireSSL="false"
cookieSlidingExpiration="true"
cookieProtection="All" >
<providers>
<clear />
<add
name="UsersRoleProvider"
type="TestProject.Web.Utility.UsersRoleProvider"
connectionStringName="TestProjectEntities"
applicationName="TestProject"
writeExceptionsToEventLog="false" />
</providers>
</roleManager>
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Optimization" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
</namespaces>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<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" />
<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" />
<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" />
</handlers>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlCeConnectionFactory, EntityFramework">
<parameters>
<parameter value="System.Data.SqlServerCe.4.0" />
</parameters>
</defaultConnectionFactory>
<!--<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>-->
</entityFramework>
</configuration>
after run api with this link:
/api/APIAccount/Login/?UserName=test1&Password=123456&RememberMe=true
its give me error:
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
To call this method, the "Membership.Provider" property must be an instance of "ExtendedMembershipProvider".
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace>
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.<>c__DisplayClass13.<GetExecutor>b__c(Object instance, Object[] methodParameters)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.<>c__DisplayClass5.<ExecuteAsync>b__4()
at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1 func, CancellationToken cancellationToken)
</StackTrace>
</Error>
I check it and see that CustomRoleManager Initializer not run in Web API and when i use view and not web api, its ok.
What should i do?
I uploaded test project in http://filebin.net/k8cqbyltac and it made by VS 2012, C#, MVC4, .Net 4.5
plaese check this URL after run for seeing error:
/api/APIAccount/Login/?UserName=test1&Password=123456&RememberMe=true
After inspecting your source I found the culprit:
Your Membership class should inherit from ExtendedMembershipProvider instead of MembershipProvider.
The WebSecurity class works with this base-class instead of the MembershipProvider, if your class doesn't inherit from that class, it will get a null-reference and it correctly tells you that it doesn't have a reference to an object of the correct type.