Session Variable not accessible in a partial class - asp.net-mvc

I have a asp.net mvc application and everything seems to be working fine on my Development machine however when I try to deploy and run the application on a server it gives me the following error:
System.NullReferenceException: Object reference not set to an instance of an object.
This happens on this line of code. All I am trying to do is set a value in the session.
I have this code inside a partial class of the Controller.
public partial class HomeController : BaseController
{
public ActionResult Index(string Value)
{
System.Web.HttpContext.Current.Session["Test"] = "world";
return View();
}
}

Thanks that led me to find solution here:
Solution 1 from ASP.NET MVC - Session is null worked for me.
"
Solution 1:
Link: HttpContext.Current.Session is null when routing requests
Got it. Quite stupid, actually. It worked after I removed & added the SessionStateModule like so:
<configuration>
...
<system.webServer>
...
<modules>
<remove name="Session" />
<add name="Session" type="System.Web.SessionState.SessionStateModule"/>
...
</modules>
</system.webServer>
</configuration>
Simply adding it won't work since "Session" should have already been defined in the machine.config.
Now, I wonder if that is the usual thing to do. It surely doesn't seem so since it seems so crude..."

Related

IIS AuthorizaUser Error

My .net mvc application is running on IIS, in release mode, when I try to access a page, it shows "An error occurred while processing your request."
After I remove the role from AuthorizeUser as shown below, I can access the page. Can anyone give advice?
Fail:
[AuthorizeUser(Roles = Role.User1)]
public class TestController : Controller
OK:
[AuthorizeUser]
public class TestController : Controller
Looks like your AD does not have roles User1.
Please go through the following link to get a better idea.
https://learn.microsoft.com/en-us/previous-versions/aspnet/web-frameworks/dd460317(v=vs.100)
Finally I solved it by adding these lines into web.config:
<modules>
<remove name="RoleManager" />
</modules>

Using dot in URL

I have the following route in RouteConfig.cs:
routes.MapRoute(
"MyLegacyRoute",
"Content/bootstrap.css",
new { controller = "Legacy", action = "GetLegacyUrl", legacyUrl = "someUrl" });
~/Content/bootstrap.css exists and rather than display its content when I navigate to http://localhost:27541/Content/bootstrap.css, I want to hit the GetLegacyUrl action in the Legacy controller.
I have added this to Web.config:
<system.webServer>
<handlers>
<add name="UrlRoutingHandler" path="/Content/*" verb="GET" type="System.Web.Routing.UrlRoutingHandler" />
...
and
<system.web>
<httpRuntime targetFramework="4.5" relaxedUrlToFileSystemMapping="true"/>
...
However when I access http://localhost:27541/Content/bootstrap.css I get this error:
Server Error in '/' Application.
Cannot create an abstract class.
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.MissingMethodException: Cannot create an abstract class.
My controller looks like this:
public class LegacyController : Controller
{
public ActionResult GetLegacyUrl(string legacyUrl)
{
return View((object)legacyUrl);
}
}
My view (GetLegacyUrl.cshtml) looks like this:
#model string
#{
ViewBag.Title = "GetLegacyUrl";
Layout = null;
}
<h2>GetLegacyUrl</h2>
The URL requested was #Model
I am trying to do this just so I can learn more about routing.
What can I do to successfully use this route?
I got it to work by putting this in RouteConfig.cs:
routes.RouteExistingFiles = true;
And by making the preCondition value an empty string:
<add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />
in this file: C:\Users\user.name\Documents\IISExpress\config\applicationhost.config
I found the answer on pg 99/115 chapter 16 in Adam Freeman's Pro ASP.NET MVC5 book.
I also removed the handler I added in the Web.config and removed the relaxedUrlToFileSystemMapping="true" since that doesn't work in MVC5.

Why might I not be getting any results from MiniProfiler?

I can't seem to get any results from MiniProfiler.
I can see the XHR POST to /mini-profiler-resources/results returning a 404. The chrome request inspector gives me a standard server 404 page.
A GET on the same URL also returns a 404, but there is a message saying that "no results were found for the specified id" (I did add the id in the querystring).
When I look at /mini-profiler-resources/results-index it just gives me an empty table with the field headings in - name, started, sql, duration, etc.
I've tried a few things - details below - at this stage I am at a loss as to what I can try next. Any pointers or suggestions for debugging this problem would be much appreciated.
Installed Packages:
MiniProfiler (v3.2.0.157)
MiniProfiler.EF6 (v3.0.11)
MiniProfiler.MVC4 (v3.0.11)
Where MVC4 also caters for MVC5. Which this project is.
Relevant Code:
protected void Application_Start()
{
MiniProfilerEF6.Initialize();
MiniProfiler.Settings.Results_List_Authorize = IsUserAllowedToSeeMiniProfilerUI;
MiniProfiler.Settings.MaxJsonResponseSize = int.MaxValue;
Database.SetInitializer<ApplicationDbContext>(null);
GlobalFilters.Filters.Add(new ProfilingActionFilter());
var copy = ViewEngines.Engines.ToList();
ViewEngines.Engines.Clear();
foreach (var item in copy)
{
ViewEngines.Engines.Add(new ProfilingViewEngine(item));
}
}
protected void Application_BeginRequest(Object source, EventArgs e)
{
if (Request.IsLocal)
{
// this IS being hit
MiniProfiler.Start();
}
}
protected void Applicaton_EndRequest()
{
MiniProfiler.Stop(discardResults: false);
}
private bool IsUserAllowedToSeeMiniProfilerUI(HttpRequest httpRequest)
{
return true;
}
In HomeController.cs:
[AllowAnonymous]
public ActionResult Index()
{
var profiler = MiniProfiler.Current;
using (profiler.Step("Doing complex stuff"))
{
using (profiler.Step("Step A"))
{
ViewBag.Title = "Home Page";
}
using (profiler.Step("Step B"))
{
Thread.Sleep(250);
}
}
return View();
}
And in MasterLayout.cshtml:
#using StackExchange.Profiling;
...
#MiniProfiler.RenderIncludes()
I've Tried:
I have set discardResults to false, like this:
protected void Applicaton_EndRequest()
{
MiniProfiler.Stop(discardResults: false);
}
I can confirm that MiniProfiler.Start() IS getting hit when the page loads.
I can also confirm that the mini-profiler-resources/ route IS being found (using Haack's Route Debugger)
I have the following item in the <handlers> section of web.config, and it is in the correct section (e.g. this guy mistakenly put it in the ELMAH config ).
<add name="MiniProfiler" path="mini-profiler-resources/*" verb="*" type="System.Web.Routing.UrlRoutingModule" resourceType="Unspecified" preCondition="integratedMode" />
I have set all my output caching to 1 second.
I was using a custom applicationhost.config file to test on a custom url.
I tried removing the custom url bindings and just using the standard localhost:51347.
I also tried putting the snippet below into applicationhost.config instead of the standard web.config.
<add name="MiniProfiler" path="mini-profiler-resources/*" verb="*" type="System.Web.Routing.UrlRoutingModule" resourceType="Unspecified" preCondition="integratedMode" />
In applicationhost.config I tried changing
<section name="handlers" overrideModeDefault="Deny" />
to
<section name="handlers" overrideModeDefault="Allow" />
I've added the following into application_start:
MiniProfiler.Settings.MaxJsonResponseSize = int.MaxValue;
As recommended in this answer, I have tried uninstalling all related packages and reinstalling them in this order:
MiniProfiler
MiniProfiler.MVC4
MiniProfiler.EF6
Update
9 days on, the bounty expired and still no joy :(
If anybody reading this in the future has ideas / suggestions, I'd really like to hear them. MiniProfiler is such a great tool and I'm disappointed that I haven't been able to get it working on this occasion.
If I do find the answer myself, I'll post it.
After running into the same issue I found the answer here which worked fine.
http://www.mukeshkumar.net/articles/mvc/performance-test-with-miniprofiler-in-asp-net-mvc
If you get an error after running application with MiniProfiler.Mvc4 or MiniProfiler.Mvc3 which state “/mini-profiler-resources/includes.js 404 not found” then simply add the following line of code in Web.Config inside web server section.
<system.webServer>
<handlers>
<add name="MiniProfiler" path="mini-profiler-resources/*"
verb="*" type="System.Web.Routing.UrlRoutingModule"
resourceType="Unspecified" preCondition="integratedMode" />
</handlers>
</system.webServer>

SignalR error with MVC

I have a class called Startup
this is the class
[assembly: OwinStartup(typeof(MyApp.Startup))]
namespace MyApp
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}
but it never runs and always give me this error
The following errors occurred while attempting to load the app.
- No assembly found containing an OwinStartupAttribute.
- No assembly found containing a Startup or [AssemblyName].Startup class.
To disable OWIN startup discovery, add the appSetting owin:AutomaticAppStartup with a value of "false" in your web.config.
To specify the OWIN startup Assembly, Class, or Method, add the appSetting owin:AppStartup with the fully qualified startup class or configuration method name in your web.config.
I have also tried to add these values in web.config but it still gives me erorr
<appSettings>
<add key="owin:AppStartup" value="MyApp.Startup, MyApp" />
<add key="owin:AutomaticAppStartup" value="true" />
</appSettings>
Please check the Startup.cs property whether is content type or compile type. The code which you have given should work fine. Just right click the file in visual studio and check properties for compile or content type. Also let me know if you are getting any compile time error.

Specifying Roles in web.config of an asp.net MVC application

I am creating an MVC application with forms auth. I am authenticating against active directory and so have created a custom RoleProvider. My application is only concerned with a small set of roles which up until now I have been defining in the appSettings section of my web.config:
<appSettings>
<add key="DirectorRole" value="Domain\Directors" />
<add key="ManagementRole" value="Domain\Managers" />
...
</appSettings>
However I have run into a couple of problems with this approach:
I cannot reference these setting in my contoller data annotations: [Authorize(Roles = ConfigurationManager.AppSettings["DirectorRole"])] as it wont compile so I have to specify the name of the group again: [Authorize(Roles = "Domain\\Directors")].
In my web.config, I would like to specify the groupsToUse for my role provider and just reference a pre-existing list, rather than maintain two seperate lists of the same set of roles.
It seems that there must be a better/reusable way to define the roles in the web.config, can someone point me in the right direction please?
I would prefer using a custom authorize attribute. Like this one.
public class MyAuthorizeAttribute : AuthorizeAttribute {
public MyAuthorizeAttribute(params string[] roleKeys) {
List<string> roles = new List<string>(roleKeys.Length);
//foreach(var roleKey in roleKeys) {
//roles.Add(ConfigurationManager.AppSettings["DirectorRole"]);
//}
var allRoles = (NameValueCollection)ConfigurationManager.GetSection("roles");
foreach(var roleKey in roleKeys) {
roles.Add(allRoles[roleKey]);
}
this.Roles = string.Join(",", roles);
}
}
In your controller, use:
[MyAuthorize("DirectorRole")]
In your web.config
<configSections>
<section
name="roles"
type="System.Configuration.NameValueFileSectionHandler,System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</configSections>
<roles>
<add key="DirectorRole" value="Domain\Directors" />
<add key="ManagementRole" value="Domain\Managers" />
</roles>
I hope this will solve your first problem just fine. And twiking a little will solve the second one too.
Please have a look at this excellent example, in which author talks about the problem you are facing.
http://www.ryanmwright.com/2010/04/25/dynamic-controlleraction-authorization-in-asp-net-mvc/

Resources