I use asp.net + MVC1.0 and in a web-page I have several forms, within each forms I have called the following function AntiForgeryToken() to generate a hidden value, and in Controller function I have a validate attribute.
When I use JMeter and capture the token using regular expression then post the token with my form to server, I found it throw such a exception:
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.FormatException: Invalid length for a Base-64 char array.
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Version Information: Microsoft .NET Framework Version:2.0.50727.3603; ASP.NET Version:2.0.50727.3082
[FormatException]: Invalid length for a Base-64 char array.
at System.Convert.FromBase64String(String s)
at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString)
at System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String serializedState)
at System.Web.Mvc.AntiForgeryDataSerializer.Deserialize(String serializedToken)
[HttpAntiForgeryException]: A required anti-forgery token was not supplied or was invalid.
at System.Web.Mvc.AntiForgeryDataSerializer.Deserialize(String serializedToken)
at System.Web.Mvc.ValidateAntiForgeryTokenAttribute.OnAuthorization(AuthorizationContext filterContext)
at System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor)
at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName)
at System.Web.Mvc.Controller.ExecuteCore()
at System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext)
at System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext)
at System.Web.Mvc.MvcHandler.ProcessRequest(HttpContextBase httpContext)
at System.Web.Mvc.MvcHandler.ProcessRequest(HttpContext httpContext)
at System.Web.Mvc.MvcHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext httpContext)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
This error page might contain sensitive information because ASP.NET is configured to show verbose error messages using <customErrors mode="Off"/>. Consider using <customErrors mode="On"/> or <customErrors mode="RemoteOnly"/> in production environments.
And I am sure the the captured token is exactly same as what we generated, why this exception happened?
Just solved, because I didn't encode the token before post to server .
Related
When i submit my WFFM forms i can see by two calls going from network,
On my QA environment its working fine but in my PROD its failed.
Please let me know , possible case for this issue
My exception log below
6840 06:57:02 ERROR The anti-forgery cookie token and form field token
do not match. Exception: System.Web.Mvc.HttpAntiForgeryException
Message: The anti-forgery cookie token and form field token do not
match. Source: System.Web.WebPages at
System.Web.Helpers.AntiXsrf.TokenValidator.ValidateTokens(HttpContextBase
httpContext, IIdentity identity, AntiForgeryToken sessionToken,
AntiForgeryToken fieldToken) at
System.Web.Helpers.AntiXsrf.AntiForgeryWorker.Validate(HttpContextBase
httpContext, String cookieToken, String formToken) at
Sitecore.Forms.Mvc.Controllers.Filters.WffmValidateAntiForgeryTokenAttribute.OnAuthorization(AuthorizationContext
filterContext) at
System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters(ControllerContext
controllerContext, IList`1 filters, ActionDescriptor actionDescriptor)
at
System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.b__19(AsyncCallback
asyncCallback, Object asyncState)
6840 06:57:02 WARN [WFFM] CurrentSession is not initialized 6840
06:57:02 WARN Web Forms for Marketers: an exception 'The anti-forgery
cookie token and form field token do not match.' has occured while
trying to execute an action ''. 9292 06:57:04 ERROR There was an
attempt to do multiple submits within a time interval, specified in
the "WFM.LimitMultipleSubmits.IntervalInSeconds" setting! Exception:
System.Security.SecurityException Message: There was an attempt to do
multiple submits within a time interval, specified in the
"WFM.LimitMultipleSubmits.IntervalInSeconds" setting! Source:
Sitecore.Forms.Mvc at
Sitecore.Forms.Mvc.Controllers.Filters.WffmLimitMultipleSubmitsAttribute.OnAuthorization(AuthorizationContext
filterContext) at
System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters(ControllerContext
controllerContext, IList`1 filters, ActionDescriptor actionDescriptor)
at
System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.b__19(AsyncCallback
asyncCallback, Object asyncState)
9292 06:57:04 WARN [WFFM] CurrentSession is not initialized 9292
06:57:04 WARN Web Forms for Marketers: an exception 'There was an
attempt to do multiple submits within a time interval, specified in
the "WFM.LimitMultipleSubmits.IntervalInSeconds" setting!' has occured
while trying to execute an action ''. ManagedPoolThread #7 06:57:42
INFO Health.PrivateBytes: 905,527,296
Finally issue solved by removed caching on WFFM forms at component level as well as in site definition too.
(But now seeking how do i cache a page alone without caching WFFM forms)
Dnn data base and files of dotnetnuke moved to new host but when starting it show error:
The page cannot be displayed because an internal server error has occurred.
i have checked log file of dnn in \Portals\_default\Logs it shows error :
2016-10-16 19:09:25,763 [WIN-MA182KN2LA7][Thread:7][ERROR] DotNetNuke.Entities.Urls.UrlRewriterUtils - System.Web.HttpException (0x80004005): Error executing child request for ~/Default.aspx. ---> System.Web.HttpException (0x80004005): No http handler was found for request type 'GET'
at System.Web.HttpApplication.MapIntegratedHttpHandler(HttpContext context, String requestType, VirtualPath path, String pathTranslated, Boolean useAppConfig, Boolean convertNativeStaticFileModule)
at System.Web.HttpServerUtility.Execute(String path, TextWriter writer, Boolean preserveForm)
at System.Web.HttpServerUtility.Execute(String path, TextWriter writer, Boolean preserveForm)
at System.Web.HttpServerUtility.Transfer(String path, Boolean preserveForm)
at DotNetNuke.Entities.Urls.AdvancedUrlRewriter.Handle404OrException(FriendlyUrlSettings settings, HttpContext context, Exception ex, UrlAction result, Boolean transfer, Boolean showDebug)
at DotNetNuke.Entities.Urls.AdvancedUrlRewriter.ProcessRequest(HttpContext context, Uri requestUri, Boolean useFriendlyUrls, UrlAction result, FriendlyUrlSettings settings, Boolean allowSettingsChange, Guid parentTraceId)
i have checked url rewitemodule in iis . it has been installed . Domain name is correct to
Handling *.aspx is not defined in iis. go into
IIS manager --> Default Website --> handler Mapping
Check if you have a mapping for aspx... ideally you should see 2 mappings for .aspx...
you can also use the command line to get the info by the following:
C:\Windows\System32\inetsrv>appcmd list config "Default Web Site" -section:handlers >"give output txt file name"
I have error for my custom asp.net
my code asp code:
IServiceConfiguration<IOrganizationService> orgConfigInfo =
ServiceConfigurationFactory.CreateConfiguration<IOrganizationService>(new Uri("http://crm.tadbirgaranbm.com/TadbirgaranMellat/XRMServices/2011/Organization.svc"));
var creds = new ClientCredentials();
creds.UserName.UserName = "user";
creds.UserName.Password = "pass";
using (_serviceProxy = new OrganizationServiceProxy(orgConfigInfo, creds))
{
// This statement is required to enable early-bound type support.
_serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
_service = (IOrganizationService)_serviceProxy;
using (context srv = new context(_service))
{
Account acc = new Account();
acc.thr_FirstName = firstname.Text;
acc.thr_LastName = lastname.Text;
acc.thr_NationalCode = nationalcode.Text;
acc.EMailAddress1 = email.Text;
acc.thr_Mobile = cellphone.Text;
acc.Telephone1 = tel.Text;
srv.AddObject(acc);
srv.SaveChanges();
alert.ForeColor = System.Drawing.Color.Green;
alert.Text = "با موفقیت ثبت شد";
}
}
and then when i run this code in my visual studio work correctly but when i run in iis i get this error
The Security Support Provider Interface (SSPI) negotiation failed.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ComponentModel.Win32Exception: The Security Support Provider Interface (SSPI) negotiation failed.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[Win32Exception (0x80004005): The Security Support Provider Interface (SSPI) negotiation failed.]
System.ServiceModel.Security.WindowsSspiNegotiation.GetOutgoingBlob(Byte[] incomingBlob, ChannelBinding channelbinding, ExtendedProtectionPolicy protectionPolicy) +6115112
System.ServiceModel.Security.SspiNegotiationTokenProvider.GetNextOutgoingMessageBody(Message incomingMessage, SspiNegotiationTokenProviderState sspiState) +1325
System.ServiceModel.Security.IssuanceTokenProviderBase1.GetNextOutgoingMessage(Message incomingMessage, T negotiationState) +91
System.ServiceModel.Security.IssuanceTokenProviderBase1.DoNegotiation(TimeSpan timeout) +586
[SecurityNegotiationException: SOAP security negotiation with 'http://crm.tadbirgaranbm.com/TadbirgaranMellat/XRMServices/2011/Organization.svc' for target 'http://crm.tadbirgaranbm.com/TadbirgaranMellat/XRMServices/2011/Organization.svc' failed. See inner exception for more details.]
System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) +14489026
System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) +622
Microsoft.Xrm.Sdk.IOrganizationService.Execute(OrganizationRequest request) +0
Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy.ExecuteCore(OrganizationRequest request) +892
Microsoft.Xrm.Sdk.Client.OrganizationServiceContext.Execute(OrganizationRequest request) +254
Microsoft.Xrm.Sdk.Client.OrganizationServiceContext.SaveChange(OrganizationRequest request, IList`1 results) +43
[SaveChangesException: An error occured while processing this request.]
Microsoft.Xrm.Sdk.Client.OrganizationServiceContext.SaveChanges(SaveChangesOptions options) +1791
crm.Reg.submit_Click(Object sender, EventArgs e) +790
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +155
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3804
this error occurs due to the time zone as the server is hosted on some other region which has a different time zone then the local timezone where the web application is running.
to solve this problem server have to manage the offset of every timezone and the simplest way to do it tom manage the time in UTC format. to learn more about UTC click here
I've just noticed that when running an application I periodically get an error message.
Server Error in '/' Application.
Buffer cannot be null.
Parameter name: buffer
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentNullException: Buffer cannot be null.
Parameter name: buffer
Stack trace:
[ArgumentNullException: Buffer cannot be null.
Parameter name: buffer]
System.IO.MemoryStream..ctor(Byte[] buffer, Boolean writable) +12627669
MemcachedProviders.Session.Common.Deserialize(HttpContext context, Byte[] serializedItems, Int32 timeout) +47
MemcachedProviders.Session.Db.SQLDbOperations.GetItem(String strSessionId, String strApplicationName, Int32 iTime, HttpContext context, Boolean lockRecord, Boolean& locked, TimeSpan& lockAge, Object& lockId, SessionStateActions& actionFlags) +1221
MemcachedProviders.Session.SessionStateProvider.GetItemExclusive(HttpContext context, String id, Boolean& locked, TimeSpan& lockAge, Object& lockId, SessionStateActions& actions) +1069
System.Web.SessionState.SessionStateModule.GetSessionStateItem() +178
System.Web.SessionState.SessionStateModule.PollLockedSessionCallback(Object state) +299
[HttpException (0x80004005): Exception of type 'System.Web.HttpException' was thrown.]
System.Web.SessionState.SessionStateModule.EndAcquireState(IAsyncResult ar) +11513726
System.Web.AsyncEventExecutionStep.OnAsyncEventCompletion(IAsyncResult ar) +107
Our application uses Enyim memcached and MemcachedProviders and runs in a load balanced environment.
The application does alot of managing of PDF reports and compiling of responses then generating a final report pdf. So we use streams quite a bit.
This problem only appears to affect our management application as we also expose a webservice and I never get the error when looking at the service definition and WSDL.
From looking at the session table in the DB I can see that they are being created but, many of them have null in the SessionItems field and the locked flag set to 1.
The data time stamps seem to correlate to the null buffer error occurances.
Is this a case of a buffer set incorrectly or maxing out?
We have some code that occasionally flushed out certain keys in the ASP.NET cache in order to make sure that we are getting up to date data from our Dynamics CRM system. It seems to work fine most of the time, however we are getting intermittent exceptions on page reloads that I suspect is related to this forced cache flushing.
Here is the error in the UnauthorizedAccessException:
Access to the path 'appDomain=/LM/W3SVC/1/ROOT-1-129326029589946795:key=Microsoft.Xrm.Client.Services.InMemoryCrmCacheProvider:Crm:Query=953227368' is denied.
In case it is helpful, here is how I am flushing the cache items:
private void Flush()
{
IDictionaryEnumerator cacheEnum = this.HttpContext.Cache.GetEnumerator();
while (cacheEnum.MoveNext())
{
var key = cacheEnum.Key.ToString();
if (key.StartsWith("Microsoft.Xrm.Client.Services.InMemoryCrmCacheProvider:Crm:Query"))
System.Web.HttpContext.Current.Cache.Remove(key);
}
}
My questions:
Is there some level of permission required to access or remove cache items? I googled this but did not find anything specific (even in MSDN).
Have you seen this error before? How did you resolve it?
UPDATE: here is the stacktrace.
Stacktrace:
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.Threading.Mutex.MutexTryCodeHelper.MutexTryCode(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.Mutex..ctor(Boolean initiallyOwned, String name, Boolean& createdNew, MutexSecurity mutexSecurity)
at System.Threading.Mutex..ctor(Boolean initiallyOwned, String name, Boolean& createdNew)
at Microsoft.Xrm.Client.Threading.MutexExtensions.Lock(String key, Int32 millisecondsTimeout, Action`1 action)
at Microsoft.Xrm.Client.Threading.MutexExtensions.Get[T](String key, Int32 millisecondsTimeout, Func`2 loadFromCache, Func`2 loadFromService)
at Microsoft.Xrm.Client.Threading.MutexExtensions.Get[T](String key, Func`2 loadFromCache, Func`2 loadFromService, Action`2 addToCache)
at Microsoft.Xrm.Client.Services.InMemoryCrmCacheProvider.InnerExecute[TRequest,TResponse,TResult](TRequest request, Func`2 execute, Func`2 selector, String selectorCacheKey)
at Microsoft.Xrm.Client.Services.CachedOrganizationService.Execute[T](MetadataServiceRequest request, Func`5 execute, Func`2 selector, String selectorCacheKey)
at Microsoft.Xrm.Client.Services.CachedOrganizationService.Execute[T](MetadataServiceRequest request, Func`2 selector, String selectorCacheKey)
at Microsoft.Xrm.Client.Services.CachedOrganizationService.Execute(Object request)
at Microsoft.Xrm.Client.Services.IOrganizationServiceExtensions.RetrieveAllEntities(IOrganizationService service, MetadataItems metadataItems, Boolean retrieveAsIfPublished)
at Microsoft.Xrm.Client.Services.InMemoryCrmCacheProvider.GetId(DynamicEntity entity)
at Microsoft.Xrm.Client.Services.InMemoryCrmCacheProvider.<GetDependencies>d__48.MoveNext()
at Microsoft.Xrm.Client.Services.InMemoryCrmCacheProvider.<GetDependencies>d__41.MoveNext()
at System.Linq.Enumerable.<SelectManyIterator>d__14`2.MoveNext()
at Microsoft.Xrm.Client.Services.InMemoryCrmCacheProvider.<GetDependencies>d__2b.MoveNext()
at Microsoft.Xrm.Client.Services.InMemoryCrmCacheProvider.<GetDependencies>d__13.MoveNext()
at System.Linq.Enumerable.<DistinctIterator>d__81`1.MoveNext()
at Microsoft.Xrm.Client.Services.InMemoryCrmCacheProvider.GetCachePolicy(Object query, Object result)
at Microsoft.Xrm.Client.Services.InMemoryCrmCacheProvider.Insert(String key, Object query, Object result)
at Microsoft.Xrm.Client.Threading.MutexExtensions.<>c__DisplayClass5`1.<Get>b__4(String k)
at Microsoft.Xrm.Client.Threading.MutexExtensions.<>c__DisplayClass2`1.<Get>b__0(Mutex _)
at Microsoft.Xrm.Client.Threading.MutexExtensions.Lock(String key, Int32 millisecondsTimeout, Action`1 action)
at Microsoft.Xrm.Client.Threading.MutexExtensions.Get[T](String key, Int32 millisecondsTimeout, Func`2 loadFromCache, Func`2 loadFromService)
at Microsoft.Xrm.Client.Threading.MutexExtensions.Get[T](String key, Func`2 loadFromCache, Func`2 loadFromService, Action`2 addToCache)
at Microsoft.Xrm.Client.Services.InMemoryCrmCacheProvider.InnerExecute[TRequest,TResponse,TResult](TRequest request, Func`2 execute, Func`2 selector, String selectorCacheKey)
at Microsoft.Xrm.Client.Services.CachedOrganizationService.Execute[T](Request request, Func`2 selector, String selectorCacheKey)
at Microsoft.Xrm.Client.Services.CachedOrganizationService.RetrieveMultiple(QueryBase query)
at Microsoft.Xrm.Client.Services.IOrganizationServiceExtensions.Using[T](Func`1 create, Func`2 action)
at Microsoft.Xrm.Client.Linq.CrmQueryProvider.Execute[TElement](QueryExpression qe, LambdaExpression projection, Delegate postMethodCall, LambdaExpression filter, Type entityType)
at Microsoft.Xrm.Client.Linq.CrmQueryProvider.Execute[TElement](Expression expression)
at Microsoft.Xrm.Client.Linq.QueryProvider.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
at System.Linq.Queryable.Single[TSource](IQueryable`1 source)
at FrontOfficeApp.Controllers.BillingController.GetBillingInstitutions(Requisition req)
at FrontOfficeApp.Controllers.BillingController.InstitutionalBillPartial(Int32 requisitionId)
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClassd.<InvokeActionMethodWithFilters>b__a()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName)
at System.Web.Mvc.Controller.ExecuteCore()
at System.Web.Mvc.MvcHandler.<>c__DisplayClass8.<BeginProcessRequest>b__4()
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass1.<MakeVoidDelegate>b__0()
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Message=Access to the path 'appDomain=/LM/W3SVC/1/ROOT-1-119328537521157948:key=Microsoft.Xrm.Client.Services.InMemoryCrmCacheProvider:Crm:Query=913126368' is denied.
Data=System.Collections.ListDictionaryInternal
UPDATE2:
We just updated to the 4.0.13 version of the SDK in order to turn off caching (actually I could only get it to work by setting the duration to 1 second, see below). This allows us to get around the issue of CRM needing to be flushed, but we are still getting the caching errors in our environment, although they look a little different now:
Message=Access to the path 'appDomain=/LM/W3SVC/1/ROOT-1-129341239247458264:key=Microsoft.Xrm.Client.Services.InMemoryCrmCacheProvider:Crm:User=00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000:Query=923237368' is denied.
Data=System.Collections.ListDictionaryInternal
For what is is worth, the context configuration I am using is below. I am adding a bounty to this question as a last ditch attempt.
<microsoft.xrm.client>
<contexts default="Crm">
<add name="Crm" type="CRM.XrmDataContext" serviceName="Default" />
</contexts>
<services default="Default">
<add name="Default" cacheProviderName="Default" />
</services>
<cache defaultProvider="Default">
<providers>
<add name="Default"
type="Microsoft.Xrm.Client.Caching.InMemoryCacheProvider, Microsoft.Xrm.Client" duration="00:00:01" />
</providers>
</cache>
</microsoft.xrm.client>
We finally figured out the answer to this issue. The problem was related to impersonation (we had it turned on in the web.config) and the fact that we were accessing XRM using a singleton. Apparently, when multiple users tried to run simultaneous CRM queries through our software, the singleton would make the connection to CRM under their user context. Apparently while this is happening, the cache for the query results are "owned" by that user context. When another user tried to run a query at the same time, they would receive a 401 status code.
The fix ended up being to turn of impersonation and do some minor refactoring so that we did not need it anymore. I imagine we could instead have allowed multiple CRM instances--though we intentionally don't do that for performance reasons.
I hope this helps anyone else who might be seeing these funky errors.
I can't imagine that the exception is actually tied to the Cache.Remove call.
Just a guess, but is it possible that the exception is related to the CacheItemRemovedCallback and not the actual removal step (not sure if the call-back is executed synchronously on the same thread)?
Can you post the full stack trace for the exception?