m_safeCertContext is an invalid handle - why does my code work in production but not in dev environment? - visual-studio

After I enabled HTTPS in my project, I started to receive an error page with this error: m_safeCertContext is an invalid handle
The code runs great in production on the web server.
I am running Visual Studio 2017 15.3.0.
I have updated sslFlags to <access sslFlags="SslNegotiateCert" />
and I have ensured iisClientCertificateMappingAuthentication is set
to <iisClientCertificateMappingAuthentication enabled="true"></iisClientCertificateMappingAuthentication>
The below are my IIS Express application pool settings:
<applicationPools>
<add name="Clr4IntegratedAppPool" managedRuntimeVersion="v4.0" managedPipelineMode="Integrated" CLRConfigFile="%IIS_USER_HOME%\config\aspnet.config" autoStart="true" />
<add name="Clr4ClassicAppPool" managedRuntimeVersion="v4.0" managedPipelineMode="Classic" CLRConfigFile="%IIS_USER_HOME%\config\aspnet.config" autoStart="true" />
<add name="Clr2IntegratedAppPool" managedRuntimeVersion="v2.0" managedPipelineMode="Integrated" CLRConfigFile="%IIS_USER_HOME%\config\aspnet.config" autoStart="true" />
<add name="Clr2ClassicAppPool" managedRuntimeVersion="v2.0" managedPipelineMode="Classic" CLRConfigFile="%IIS_USER_HOME%\config\aspnet.config" autoStart="true" />
<add name="UnmanagedClassicAppPool" managedRuntimeVersion="" managedPipelineMode="Classic" autoStart="true" />
<applicationPoolDefaults managedRuntimeLoader="v4.0">
<processModel loadUserProfile="true" />
</applicationPoolDefaults>
</applicationPools>
full text from error page:
Server Error in '/' Application.
m_safeCertContext is an invalid handle.
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.Security.Cryptography.CryptographicException: m_safeCertContext is an invalid handle.
Source Error:
Line 383: HttpClientCertificate httpCert = HttpContext.Current.Request.ClientCertificate;
Line 384: X509Certificate2 x509Cert = new X509Certificate2(httpCert.Certificate);
Line 385: _subject = x509Cert.Subject;
Line 386: _sCustomerId = CustomerQueries.getCustomerId(_subject);
Line 387: LoadCustomerAttributes(CustomerQueries.getCustomerAttributes(_sCustomerId));
Source File: C:\$TFS\Reports\Projects\WebMaster\Customers\Classes\Customer.cs Line: 385
Stack Trace:
[CryptographicException: m_safeCertContext is an invalid handle.]
System.Security.Cryptography.X509Certificates.X509Certificate.ThrowIfContextInvalid() +12505161
System.Security.Cryptography.X509Certificates.X509Certificate.get_Subject() +14
ReportsRG.Projects.WebMaster.Customers.Classes.Customer.GetUserDataFromCertificate() in C:\$TFS\SMRT\Dev\ReportsRG\Projects\WebMaster\Customers\Classes\Customer.cs:385
ReportsRG.Projects.WebMaster.Customers.Classes.Customer..ctor() in C:\$TFS\SMRT\Dev\ReportsRG\Projects\WebMaster\Customers\Classes\Customer.cs:322
MVCPages.Controllers.SmrtController.Index() in C:\$TFS\SMRT\Dev\MVCPages\Controllers\SmrtController.cs:39
lambda_method(Closure , ControllerBase , Object[] ) +61
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +157
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
System.Web.Mvc.Async.<>c.<BeginInvokeSynchronousActionMethod>b__9_0(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22
System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
System.Web.Mvc.Async.<>c__DisplayClass11_0.<InvokeActionMethodFilterAsynchronouslyRecursive>b__0() +58
System.Web.Mvc.Async.<>c__DisplayClass11_2.<InvokeActionMethodFilterAsynchronouslyRecursive>b__2() +228
System.Web.Mvc.Async.<>c__DisplayClass7_0.<BeginInvokeActionMethodWithFilters>b__1(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
System.Web.Mvc.Async.<>c__DisplayClass3_6.<BeginInvokeAction>b__4() +35
System.Web.Mvc.Async.<>c__DisplayClass3_1.<BeginInvokeAction>b__1(IAsyncResult asyncResult) +100
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
System.Web.Mvc.<>c.<BeginExecuteCore>b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState) +11
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +45
System.Web.Mvc.<>c.<BeginExecute>b__151_2(IAsyncResult asyncResult, Controller controller) +13
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c.<BeginProcessRequest>b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState) +28
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9850009
System.Web.<>c__DisplayClass285_0.<ExecuteStepImpl>b__0() +26
System.Web.StepInvoker.Invoke(Action executionStep) +107
System.Web.<>c__DisplayClass4_0.<Invoke>b__0() +23
Microsoft.AspNet.TelemetryCorrelation.TelemetryCorrelationHttpModule.OnExecuteRequestStep(HttpContextBase context, Action step) +64
System.Web.<>c__DisplayClass284_0.<OnExecuteRequestStep>b__0(Action nextStepAction) +56
System.Web.StepInvoker.Invoke(Action executionStep) +91
System.Web.<>c__DisplayClass4_0.<Invoke>b__0() +23
Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule.OnExecuteRequestStep(HttpContextBase context, Action step) in /_/WEB/Src/Web/Web/ApplicationInsightsHttpModule.cs:164
System.Web.<>c__DisplayClass284_0.<OnExecuteRequestStep>b__0(Action nextStepAction) +56
System.Web.StepInvoker.Invoke(Action executionStep) +91
System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +9956298
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +163

The call stack at least gives enough hints on what to look for next.
Line 383: HttpClientCertificate httpCert = HttpContext.Current.Request.ClientCertificate;
Line 384: X509Certificate2 x509Cert = new X509Certificate2(httpCert.Certificate);
Line 385: _subject = x509Cert.Subject;
This piece of code tries to grab the client certificate sent by the browser, and then access its Subject property. This access attempt failed and an exception happened,
[CryptographicException: m_safeCertContext is an invalid handle.]
System.Security.Cryptography.X509Certificates.X509Certificate.ThrowIfContextInvalid() +12505161
System.Security.Cryptography.X509Certificates.X509Certificate.get_Subject() +14
Since .NET Framework in general wraps up native Windows API, so the exception itself can be quite confusing.
"The code runs great in production on the web server", so that I can assume your server administrators have configured this production machine to know how to build full chains for client certificates (very common server configuration), but you might not have done the same on your development machine. Talk to the server administrators and learn what you missed.
In the meantime, you might set a break at line 384 and analyze more details of httpCert. That might help you find out what settings are missing.

I was updating the wrong ApplicationHost.config file.
The correct one is located at .vs\config in the solution root.
I was updating the one located at: C:\Users\[username]\Documents\IISExpress\config\
Once I updated the correct ApplicationHost.config file, the code started working in my local development environment.

Related

MVC using VS: Why am I getting an error when using View() but not when I use View(viewname)?

I am getting a strange error when using the following:
public ActionResult PostToPayPal(WalkerRegoViewModel walkerVM, string submit)
...
return View(paypal);
But when I specify the ViewName it works (nothing else has changed)?
public ActionResult PostToPayPal(WalkerRegoViewModel walkerVM, string submit)
...
return View("PostToPayPal", paypal);
The error I get is:
Object reference not set to an instance of an object.
Exception Details:
System.NullReferenceException: Object reference not set to an instance of an object.
Here is the Stack Trace:
Server Error in '/' Application.
Object reference not set to an instance of an object.
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.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
An unhandled exception was generated during the execution cf the current web request. Information regarding the origin and locaticn of the exception can be identified using the exception stack trace below.
Stack Trace:
[NullReferenceException: Object reference not set to an instance of an object.]
Walk.Controllers.RegisterController.PostToPayPal(WalkerRegoViewModel walkerVM, String submit) in C:\dev\Walk\Walk\Controllers\RegisterController
lambda_method(Closure , ControllerBase , Object[] ) +147
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary.2 parameters) +169
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary-2
System.Web.Mvc.Async.oc.b 9_0(IAsyncResult asyncResult, Actionlnvocation innerInvokeState) +22
System.Web.Mvc.Async.WrappedAsyncResult.2.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase.1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
System.Web.Mvc.Async.oc DisplayClass11_0.b 0() +58
System.Web.Mvc.Async.oc DisplayClass11_2.b 2() +228
System.Web.Mvc.Async.oc DisplayClass7_0.b 1(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult.1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase.1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
System.Web.Mvc.Async.oc DisplayClass3_6.b 4() +35
System.Web.Mvc.Async.oc DisplayClass3_1.b 1(IAsyncResult asyncResult) +100
System.Web.Mvc.Async.WrappedAsyncResult.1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase.1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
System.Web.Mvc.oc.b 152_1(IAsyncResult asyncResult, ExecuteCoreState innerState) +11
System.Web.Mvc.Async.WrappedAsyncVoid.1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase.1.End() +49
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +45
System.Web.Mvc.oc.b 151_2(IAsyncResult asyncResult, Controller controller) +13
System.Web.Mvc.Async.WrappedAsyncVoid.1.CallEndDelegate(IAsyncResult asyncResult) +22
System.Web.Mvc.Async.WrappedAsyncResultBase.1.End() +49

Error when installing uCommerce with Umbraco 7

I'm having issues when trying to install uCommerce into Umbraco 7. I have tried installing via the online package and via a local package I downloaded from their website. Both are failing with the same error message.
This is installing it on Umbraco 7.2.7 using uCommerce 6.8.2
2015-10-20 10:59:23,832 [114] ERROR Umbraco.Core.UmbracoApplicationBase - [P2760/T103/D30] An unhandled exception occurred
System.ArgumentException: The relative virtual path 'function sortCampaignItems(){
UmbClientMgr.openModalWindow('/umbraco/ucommerce/marketing/SortCampaignItems.aspx?id=' + UmbClientMgr.mainTree().getActionNode().nodeId, 'Sort',true,600,450);
}' is not allowed here.
at System.Web.VirtualPath.Create(String virtualPath, VirtualPathOptions options)
at System.Web.VirtualPathUtility.ToAbsolute(String virtualPath, String applicationPath)
at Umbraco.Core.IO.IOHelper.ResolveUrl(String virtualPath)
at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at Umbraco.Web.Editors.BackOfficeController.GetLegacyActionJs(LegacyJsActionType type)
at Umbraco.Web.Editors.BackOfficeController.Application()
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.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.<>c__DisplayClass2b.<BeginInvokeAction>b__1c()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Can anyone help with any suggestions of resolving this matter? I've been at this for hours and don't seem be getting anywhere.
Thanks
Answered by Jesper Nielsen via http://eureka.ucommerce.net/#!/question/1649/Error-when-installing-uCommerce-with-Umbraco-7
Hi Andy,
I get the same error when installing on Umbraco 7.2.7. We will look into the cause of this.
I have installed version 6.8.2 of uCommerce on Umbraco 7.2.8 without problems.
Is it possible for you to use Umbraco 7.2.8?
Sorry for the inconvenience!
Kind regards, Jesper

Why won't Visual Studio break on this unhandled exception?

When submitting a form, a Yellow Screen of Death appeared even while in Debug mode in Visual Studio. The problem I had is solved, it was a missing resource value, but I'm interested in why I'm not able to break on the exception.
I tried the following, but nothing changed the situation:
Stepping through the code.
Changing the Debug -> Exceptions settings.
Checking Enable .NET Framework source stepping and Enable source server support.
How can such an exception be caught, or why is it not possible to catch it?
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: Value cannot be null.
Parameter name: value
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:
[ArgumentNullException: Value cannot be null.
Parameter name: value]
System.ComponentModel.DataAnnotations.ValidationContext.set_DisplayName(String value) +52015
System.Web.Mvc.<Validate>d__1.MoveNext() +135
System.Web.Mvc.<Validate>d__5.MoveNext() +318
System.Web.Mvc.DefaultModelBinder.OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext) +139
System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model) +66
System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +1367
System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +449
System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +317
System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +117
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343
System.Web.Mvc.Controller.ExecuteCore() +116
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8970061
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
It is not possible to break on this exception, because Microsoft's public Symbol Server does not provide source code for everything.
Adding a breakpoint via the dialog to System.ComponentModel.DataAnnotations.ValidationContext.set_DisplayName will break, but Visual Studio will say that there is no source code available.
Looks like you have some dataAnnotationAttribute for model field, so asp.net takes care about it - before your request fires breakpoint in controller

Issue with System.Web.WebPages after installing MVC4

I have installed MVC4 and an MVC3 app that I have is now causing me problems. I get the error :
Could not load file or assembly 'System.Web.WebPages, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference
However, I cannot find any references in my code to v2 of WebPages, and I am wondering why I am getting this error. Can anybody help?
EDIT : Here is the full stack trace :
[FileLoadException: Could not load file or assembly 'System.Web.WebPages, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)]
ljMVC.Helpers.EditableHelpers.Editable(HtmlHelper helper, String htmlElement, String cssId, String defaultContent, Object htmlAttributes) in C:\Users\M\Desktop\Development\ASP.NET projects\ljMVC\ljMVC\ljMVC\Helpers\EditableHelpers.cs:90
ASP._Page_Areas_Gameplan_Views_MainGP_Index_cshtml.Execute() in e:\web\lovelyjubbl\htdocs\Areas\Gameplan\Views\MainGP\Index.cshtml:85
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +208
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +89
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +78
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +199
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +107
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +291
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
System.Web.Mvc.<>c_DisplayClass1c.b_19() +23
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func1 continuation) +264
System.Web.Mvc.<>c__DisplayClass1e.<InvokeActionResultWithFilters>b__1b() +20
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList1 filters, ActionResult actionResult) +176
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +329
System.Web.Mvc.Controller.ExecuteCore() +115
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +94
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
System.Web.Mvc.<>c_DisplayClassb.b_5() +37
System.Web.Mvc.Async.<>c_DisplayClass1.b_0() +21
System.Web.Mvc.Async.<>c_DisplayClass81.<BeginSynchronous>b__7(IAsyncResult _) +12
System.Web.Mvc.Async.WrappedAsyncResult1.End() +55
System.Web.Mvc.<>c_DisplayClasse.b_d() +31
System.Web.Mvc.SecurityUtil.b_0(Action f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +23
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +59
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8970061
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
Here:
EditableHelpers.cs:90
I guess you are using some NuGet or something that depends on WebPages 2.0 (a.k.a System.Web.WebPages, Version=2.0.0.0). You probably updated this NuGet or whatever it is and now you have dependency with this assembly.

FormsAuthentication.SetAuthCookie throwing NullReferenceException in async action

I am finding that FormsAuthentication.SetAuthCookie is throwing a NullReferenceException - Object reference not set to an instance of an object inside an async action on an azure website.
I found the following:
http://connect.microsoft.com/VisualStudio/feedback/details/743350/formsauthentication-setauthcookie-throws-nullreferenceexception-if-called-in-an-async-action-in-mvc4
However I already have
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
set and my code works fine locally I only experience the problem when I deploy to azure. I am using Azure Websites (https://www.windowsazure.com/en-us/home/scenarios/web-sites/), it was my understanding that this uses the web.config normally? I have also tried adding the appsetting through the Azure control panel
And adding .ConfigureAwait(false); to my awaited method but have had no luck.
The following code will throw the exception
public class TestController : Controller
{
public async Task<ActionResult> Index()
{
var httpResponse = await new HttpClient().GetAsync("http://www.google.com");
FormsAuthentication.SetAuthCookie("test", true);
return View();
}
}
Anyone know how I can get this to work?
UPDATE:
Stack Trace:
[NullReferenceException: Object reference not set to an instance of an object.]
System.Threading.Tasks.<>c__DisplayClass1c.<GetRethrowWithNoStackLossDelegate>b__1b(Task task) +91
System.Threading.Tasks.TaskHelpersExtensions.ThrowIfFaulted(Task task) +15
System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult asyncResult) +77
System.Web.Mvc.Async.<>c__DisplayClass3f.<BeginInvokeAsynchronousActionMethod>b__3e(IAsyncResult asyncResult) +16
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +50
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +59
System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +240
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +12
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +50
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +31
System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +23
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +128
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +50
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +26
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +25
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +41
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +25
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +28
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__4(IAsyncResult asyncResult) +28
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +25
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +31
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +23
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +59
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult ar) +96
UPDATE
I found it works if setting the Cookie manually
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, "test", DateTime.Now, DateTime.Now.AddMinutes(30), true, null, FormsAuthentication.FormsCookiePath);
string encTicket = FormsAuthentication.Encrypt(ticket);
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
I'm not going to answer the question though as would like to know why FormsAuthentication.SetAuthCookie is throwing the exception and why it is behaving differently on Azure Websites
This issue is not specific to Azure - the method FormsAuthentication.SetAuthCookie will throw a null reference exception in an async action when an await statement is called before FormsAuthentication.SetAuthCookie is called.
The easiest solution is to use the following:
Response.Cookies.Add(FormsAuthentication.GetAuthCookie("user-1", true));
An alternative would be to specify the ticket creation yourself:
var ticket = new FormsAuthenticationTicket(
2,
"user-1",
DateTime.Now,
DateTime.Now.AddDays(2),
true,
String.Empty,
"/");
var encTicket = FormsAuthentication.Encrypt(ticket);
Response.Cookies.Add(new HttpCookie(".AUTH", encTicket));
At present time, .NET 4.5 is not supported in Windows Azure Web Sites. You will need to downgrade your project to .NET 4.0 which will also mean you will need to rewrite the code to not use async.
You could attempt to bin deploy the .NET 4.5 assemblies that are required by your application
you can change this way also it up to you
public ActionResult Index()
{
var t1 = Task.Run(() => HttpClient().GetAsync("http://www.google.com"));
t1.Wait();
FormsAuthentication.SetAuthCookie("test", true);
return View();
}
this way work for me and i got idea from GlennMorton 1st answer
thanks.

Resources