Issue accessing Session state from user control - vb.net

I am getting the following error when trying to pull from the Session state in the code behind of a user control.
Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive. Please also make sure that System.Web.SessionStateModule or a custom session state module is included in the \\ section in the application configuration.
Here is the config that I have in the section
<sessionState mode="InProc" cookieless="false" timeout="20"/>
<globalization requestEncoding="utf-8" responseEncoding="utf-8"/>
<pages enableSessionState="true"></pages>
<httpModules>
<remove name="Session" />
<add name="Session" type="System.Web.SessionState.SessionStateModule"/>
</httpModules>
Here is the how I reference in on the user control itself. This is done in Page_Load
If Not Session("ADName") Is Nothing AndAlso Session("ADName").length > 0 Then
'Do Stuff
End If
And my control declaration
<%# Control Language="vb" AutoEventWireup="false" CodeBehind="UCHeader.ascx.vb" Inherits="PO.Web.UCHeader"
TargetSchema="http://schemas.microsoft.com/intellisense/ie5" %>
What would be causing this issue. I am trying to build locally and get this issue, so it is not related to IIS at all. I am migrating this app from 2.0 to 3.5 and started getting the error at that time. Let me know if you need any more info. Thanks.

Related

asp.net core out-of-process fails to start correctly

I'm attempting to us the RunFromPackage App Setting for an Azure Web Site.
I'm using the following stack
asp.net core (out-of-process)
Targeting .Net Framework 4.7.2
and I can no longer get my web application to run correctly. when I hit the url all I get is
"The page cannot be displayed because an internal server error has occurred."
in the response.
I have launched my application using the Kudu powershell window with the command
".{applicationName}.exe"
and it start up fine. No errors or anything
Viewing the event viewer logs all I see is
APPLICATION_MANAGER::~APPLICATION_MANAGER | this=000001D1CD999A60 [TID 8872] [PID 8028]
When turning on the Failed Request Tracing Logs I see the following relevant information
URL_CACHE_ACCESS_START RequestURL="/favicon.ico" 15:37:30.729
URL_CACHE_ACCESS_END PhysicalPath="", URLInfoFromCache="false", URLInfoAddedToCache="true", ErrorCode="The operation completed successfully.
(0x0)" 15:37:30.729
GENERAL_GET_URL_METADATA PhysicalPath="", AccessPerms="545" 15:37:30.729
HANDLER_CHANGED OldHandlerName="", NewHandlerName="aspNetCore", NewHandlerModules="AspNetCoreModule", NewHandlerScriptProcessor="", NewHandlerType="" 15:37:30.729
MODULE_SET_RESPONSE_ERROR_STATUS
Warning ModuleName="IIS Web Core", Notification="BEGIN_REQUEST", HttpStatus="500", HttpReason="Internal Server Error", HttpSubStatus="0", ErrorCode="Access is denied.
(0x80070005)", ConfigExceptionInfo=""
I have tried to turn on the asp.net core module logging but I get no log files. I have also tried to turn on the stdoutlog but nothing is appearing to log.
Here is a copy of my web.config
<configuration>
<system.webServer>
<security>
<access sslFlags="SslNegotiateCert" />
</security>
<serverRuntime uploadReadAheadSize="30000000" />
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="%LAUNCHER_PATH%" stdoutLogEnabled="true" stdoutLogFile="\\?\%home%\LogFiles\stdout" hostingModel="OutOfProcess" arguments="%LAUNCHER_ARGS%">
<handlerSettings>
<handlerSetting name="debugFile" value="\\?\%home%\LogFiles\aspnetcore-debug.log" />
<handlerSetting name="debugLevel" value="FILE,TRACE" />
</handlerSettings>
</aspNetCore>
</system.webServer>
</configuration>
I'm not really sure what is going on. All I can gather is something is going wrong with the IIS Module. from the error message it appears that it cannot read or process my web.config ErrorCode="Access is denied."
Strangely enough I had a previous build of the application up and running. I have tried to isolate the changes that may have broke the site but I cant seem to find out what has cause this.
It appears that this was due to the fact I was trying to get only client authentication on one endpoint.
The following setting
<access sslFlags="SslNegotiateCert" />
in the web.config, and Require incoming Certificate in the App Settings caused my issue.
I then tried the feature of "Certificate exclusion paths" but having this and the web.config access node makes the web server very upset and causes the error message
"The page cannot be displayed because an internal server error has occurred."
I had to remove the node from my web.config file, leave the Required SSL, and set my Certificate Exclusion path and everything turned back online.

How can i tell if my connectionStrings section is encrypted or not?

I have followed Microsoft's instructions here in order to encrypt my connection strings for my application. I have opted to move my connection strings to their own configuration file, connections.config. My code is as posted below (bottom of page) - nearly identical to the snippets provided by Microsoft. After performing the operations, the command: MessageBox.Show(String.Format("Protected={0}", connectionStringsSection.SectionInformation.IsProtected)) prints True, indicating the operation was successful.
However, Microsoft states that "The following configuration file fragment shows the connectionStrings section after it has been encrypted:"
configProtectionProvider="DataProtectionConfigurationProvider">
<EncryptedData>
<CipherData>
<CipherValue>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAAH2... </CipherValue>
</CipherData>
</EncryptedData>
This does not appear to be true in my case. Despite printing True when asking if my sectionInformation.IsProtected, Both my app.config and my connections.config files remain unchanged when visually inspecting them. This leads me to my questions:
Does the description of my problem indicate that in fact my section is not protected after all?
Why is sectionInformation.IsProtected printing True, but no <EncryptedData> attributes have been added to my sectionInformation?
If you carefully read Microsoft's instructions in the link above, they provide explanations for creating both your own connections.config file outside of app.config, as well as encrypting your connections section. However, they do not explicitly say that following their instructions for encrypting connectionStrings section will do so in the external configuration file, connections.config as well. Is the attribute tag in app.config, <connectionStrings configSource="connections.config" />, sufficient to ensure this behavior?
How do I test that my application's connection strings are indeed encrypted correctly, other than a MessageBox printing the IsProtected property?
NOTE
This is NOT an ASP.Net application, this is a Winforms application
I have tested the above with my connectionStrings in both their own connections.config file, as well as within app.config file, and the result is the same.
The relevant sections of my code are posted below:
*app.config*
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<!-- ... -->
</configSections>
<system.diagnostics>
<!-- ... -->
</system.diagnostics>
<userSettings>
<!-- ... -->
</userSettings>
<connectionStrings configSource="connections.config" />
</configuration>
*connections.config*
<connectionStrings>
<!--Manhattan Connection-->
<add name="MANHATTAN"
connectionString="Data Source=xxx;Initial Catalog=xxx;Persist Security Info=False;Integrated Security=False" />
<add name="DENVER"
connectionString="Data Source=xxx;Initial Catalog=xxx;Persist Security Info=False;Integrated Security=False" />
<add name="DESMOINES"
connectionString="Data Source=xxx;Initial Catalog=xxx;Persist Security Info=False;Integrated Security=False" />
</connectionStrings>
*The connection source code*
Private Sub ToggleConfigurationEncryption(ByVal executableName As String)
Try
Dim configManager = ConfigurationManager.OpenExeConfiguration(executableName)
Dim connectionStringsSection = configManager.GetSection("connectionStrings")
If connectionStringsSection.SectionInformation.IsProtected Then
connectionStringsSection.SectionInformation.UnprotectSection()
Else
connectionStringsSection.SectionInformation.ProtectSection("DataProtectionConfigurationProvider")
End If
configManager.Save()
MessageBox.Show(String.Format("Protected={0}", connectionStringsSection.SectionInformation.IsProtected))
Catch ex As Exception
ExceptionController.LogException(ex)
ExceptionController.DisplayException(ex)
End Try
End Sub
Your issue is happening in your if statement.
If connectionStringsSection.SectionInformation.IsProtected Then
connectionStringsSection.SectionInformation.UnprotectSection()
...
This example shows how to toggle between encrypting and decrypting. In the code posted by you, you're simply decrypting the file if it's already encrypted. Your code should be something like this:
If (Not connectionStringsSection.SectionInformation.IsProtected) Then
connectionStringsSection.SectionInformation.ProtectSection("DataProtectionConfigurationProvider")
End If
You only want to encrypt if the file has not been encrypted. Don't worry about decrypting the file and trying to read. It will automatically decrypt it for you.
I don't see the how you're calling the ToggleConfigurationEncryption method. You need to pass the correct name of the output config file. After you launch your app (if in debug mode) you can go to project directory in bin\debug folder and look for your connections.config file. When you open it you'll see that it's encrypted.

ImageResizing Not Working In Hosting

I have an asp.net mvc project. I installed imageresizing nuget packages. It's working in local.
When I published to my hosting then it's not working.
I set IIS situation integrated and classic but still didn't work.
I couldn't solve, can you help please? Thanks.
The following definitions are exist in web.config
<resizer>
<plugins>
<add name="MvcRoutingShim" />
<add name="DiskCache" />
<add name="SimpleFilters" />
<add name="PrettyGifs" />
</plugins>
</resizer>
<modules runAllManagedModulesForAllRequests="true">
<add name="ImageResizingModule" type="ImageResizer.InterceptModule" />
</modules>
The self-diagnostics page at /resizer.debug explains the configuration issues present on your hosting environment
Image resizer diagnostic sheet 24.11.2014 22:15:04
2 Issues detected:
(Critical): Grant the website SecurityPermission to call UrlAuthorizationModule.CheckUrlAccessForPrincipal
Without this permission, it may be possible for users to bypass UrlAuthorization rules you have defined for your website, and access images that would otherwise be protected. If you do not use UrlAuthorization rules, this should not be a concern. You may also re-implement your security rules by handling the Config.Current.Pipeline.AuthorizeImage event.
DiskCache(ConfigurationError): Not working: Your NTFS Security permissions are preventing the application from writing to the disk cache
Please give user read and write access to directory "D:\inetpub\adafirin.com\www\imagecache" to correct the problem. You can access NTFS security settings by right-clicking the aformentioned folder and choosing Properties, then Security.

ASP.NET MVC4 routing ignored for static files

I have an ASP.NET MVC3 application .NET4 in which a routing exists for content files, which are served from a resource inside a class library.
Routing is configured as follows
routes.MapRoute("Resources", "Default{Content}/{*contentpath}", new {controller = "Resource", action="GetResource"});
So if there is a request DefaultMvcScripts/test.js, the GetResource method will be called.
However, when converted to MVC4 ,.NET4.5 this doesn't work anymore, GetResource is not called anymore, it bypasses routing even if I put
routes.RouteExistingFiles = true;
For a request DefaultMvcScript/test (without extension), routing is not ignored (I can see GetResource being called).
Can I have the old behaviour back, so that even if I specify an extension, routing is honoured.
I think you're just missing the last step - you need to configure your app so that the handler pipeline pays attention to requests for static files.
In they system.webserver section of the web config you need to add a handler for the static files you want to serve. You need to use the TransferRequestHandler
<add name="staticHandler" path="*.js" verb="GET" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersion4.0"/>
See Jon Galloway's article for a complete description
http://weblogs.asp.net/jongalloway/asp-net-mvc-routing-intercepting-file-requests-like-index-html-and-what-it-teaches-about-how-routing-works
Apparently, adding this to the web.config restores previous behaviour:
<modules>
<remove name="UrlRoutingModule-4.0" />
<add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />
</modules>
The preCondition="" seems to be the trick.
Source: http://www.britishdeveloper.co.uk/2010/06/dont-use-modules-runallmanagedmodulesfo.html

mvc4, trouble with WebMatrix reference and Windows authentication

I have a maddening situation here with an MVC4 site. At the outset, you need to know it uses Windows authentication, and I also want to use simplemembership roles (but I don't think this is working--but this is not the focus of my question). Basically, the site works on my dev machine (with IIS Express) and a test machine (with regular IIS). But it doesn't work in production environment. We get an error "could not load file or assembly WebMatrix.WebData, version=2.0.0.0.
The WebMatrix.WebData reference has CopyLocal = False. (This works in dev and test.) If I set CopyLocal = True, then the authentication goes haywire. Specifically, when you visit the site, it attempts a redirect to login.aspx (obviously not an MVC component). So, my question is Why is this happening? How do I fix?
Here's what I've got under my system.web element in the config:
<roleManager enabled="true">
<providers>
<clear/>
<add name="simple" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData"/>
</providers>
</roleManager>
<membership>
<providers>
<clear/>
</providers>
</membership>
<authentication mode="Windows" />
I've played around with this quite a bit trying to understand the problem, but I don't really know what I'm doing with this config section/what all can be done. I wonder if there's a problem clearing all the membership providers.... while trying to use the SimpleRoleProvider. (I tried cutting out SimpleRoleProvider, but this had no effect on problem.)