MVC with IIS 6 - c#

I've read a couple of posts on this issue but still can't seem to get MVC working on IIS 6. I've mapped .mvc to aspnet_isapi.dll in IIS but get a 404 when I browse to my mapped URL which looks like this
RouteTable.Routes.MapRoute("action", "api.mvc/{controller}/{action}", new {action = "Index"});
I then browse to //localhost/Web.Site/api.mvc/Users/List but get a 404 returned
same happens for
//localhost/Web.Site/api.mvc/Users/
I have a UsersController with List and Index that both returns a ViewAction
Is there anything else I need to do? Or have I missed something
cheers
also.............
I should point out that my redirect my default page in the website is working
eg my default code behind has
HttpContext.Current.RewritePath(Request.ApplicationPath, false);
IHttpHandler httpHandler = new MvcHttpHandler();
httpHandler.ProcessRequest(HttpContext.Current);
so the default "/" request does get correctly routed via this in the global.asax.cs
RouteTable.Routes.MapRoute("default", "", new {controller="Home", action = "Index" });
not sure if that helps anyone

Have you unchecked the "Verify that file exists" box on the extension mapping?

Try deleting your default.aspx page and make sure you have this in your web.config:
<httpModules>
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing"/>
</httpModules>

Related

ASP NET MVC 5: Session ends suddenly

right now i work on an already existing ASP.NET MVC Project, which has the problem that the session sometimes suddenly ends and the user gets redirected to the login page. Today i noticed something, the login page is always loaded in the background:
I don't have much Experience with ASP.NET MVC so i wanted to ask, what could be the reason this always gets loaded. The code is not documented so i could not find a reason for it. I use IIS 8 for deploying.
Update:
I have now tracked with Fiddler and i saw something, at first i thought that the session cookies gets dropped or replaced turns out it doesnt. Its there even on the login page.
Update 2:
I have now validated that the cookie is still in place and the login info is still stored after this forced logout. Is there a common issue in ASP NET which can cause that a session is still saved but not recognized anymore? Turns out it could be this ActionFilter:
namespace backend.Models.ActionFilter
{
public class HasUserId : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.Session.GetInt32("UserId") == null)
{
System.Diagnostics.Debug.WriteLine("Session is not there anymore");
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { action = "Login", controller = "Account" }));
}
}
}
}
Update 3:
I think I have found the problem, the session state gets stored 'In-process' i have now changed it to 'State Service'. I hope this will solve my problem. Is it normal that the login still works even when the 'ASP NET State Service' is halted? This is my config:
<system.web>
<sessionState
mode="StateServer"
stateConnectionString="tcpip=127.0.0.1:42424"
stateNetworkTimeout="20"
timeout="240">
</sessionState>
</system.web>
This problem occurs if the login page is as the start page. You can change this by modifying the filter file and specifically in routes.MapRoute.
For more information you can view here
If you want to change redirection via IIS, you can not do that.
The answer for my problem was to change the handling of the session state from 'In-process' to 'Out-of-process'.

URL Extension in MVC 4 Not working after update

I've just updated my MVC 3 to MVC 4
However now my URL extension methods are not binding. It does not seems to think Url has the method PSUrl(). They are still in the same name space..
Method:
public static string PSUrl(this UrlHelper url)
View:
#Url.PSUrl()
Does MVC4 have a different way of extending? I cant seem to find anything on it.
The updates must have removed a name space from my views web.config (Note: there are two web.configs, check the one inside the Views folder!)
Re-adding the line to use my extensions, resolves it again.
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="MyProject.Extensions" />

C# ASP.Net MVC: RedirectFromLoginPage always goes to default url, and not to returnurl

I have an MVC4 application with Membership logon (through FormsAuthentication).
This is defined in web.config as follows.
My default url is home root (~/):
<roleManager enabled="true" />
<authentication mode="Forms">
<forms defaultUrl="~" loginUrl="~/Account" />
</authentication>
In my AccountController in the Login post method, following code is relevant.
This code is executed when the user clicks on the login with valid credentials.
if (Membership.ValidateUser(creds.Username, creds.Password))
{
FormsAuthentication.RedirectFromLoginPage(creds.Username, false);
return null;
}
Now, if I'm navigating (anonymously) to: ~/Admin, I get redirected to ~/Account to log in, which is perfect. I can see that the url is formed as follows:
http://localhost:23759/Account?ReturnUrl=%2fAdmin
But, when I succesfully login, I get redirected to home (~/) instead of ~/Admin
Please help!
Many thanks!
Edit: Found the actual issue: it was the post method that wasn't receiving the querystring
I found the solution!
Thanks to FlopScientist, who got me thinking further.
It was indeed because I was doing a POST method, which did not take the QueryString from the GET into account.
First I had this in my View:
#using (Html.BeginForm("Index", "Account")
{
<div class="LoginBox">
//Etc...
</div>
}
I have updated it to following:
#using (Html.BeginForm("Index", "Account", new { ReturnUrl = Request.QueryString["ReturnUrl"] }, FormMethod.Post))
{
//Etc...
}
Now I can actually see a querystring in my debug and I do get a correct redirect!
There doesn't seems any issue with your Return URL: [ %2f is / ] localhost:23759/Account?ReturnUrl=%2fAdmin
So, what remains is to do some checks as to what is causing such behaviour.
1.) Are you sure that the return page as specified in the return url:
localhost...?ReturnUrl=%2fAdmin
actually exists and your user has access to it?Here Admin is a folder, so you must have a page default.aspx inside this folder. If it does not exists, RedirectFromLoginPage by default will send you to DefaultURL.
2.) Also, Try using FormsAuthentication.GetRedirectUrl() method to see what happens.
if (Membership.ValidateUser(creds.Username, creds.Password))
{
Response.Redirect(FormsAuthentication.GetRedirectUrl(username, false));
}
3.) OR does this works ? [ Recommended for debug purposes ]
if (!string.IsNullOrEmpty(Request.QueryString["ReturnUrl"]))
{
Response.Redirect("~/Admin");
}
Lastly make sure there are NO such code lines redirecting user to other pages/DefaultURL.
It probably because that path is not detected as same app path:
By default, the ReturnUrl variable must refer to a page within the
current application. If ReturnUrl refers to a page in a different
application or on a different server, the RedirectFromLoginPage method
redirects to the URL in the DefaultUrl property. If you want to allow
redirects to a page outside the current application, you must set the
EnableCrossAppRedirects property to true using the
enableCrossAppRedirects attribute of the forms configuration element.
from: http://msdn.microsoft.com/en-US/library/1f5z1yty.aspx

Output (server-side) caching of ashx files

I am trying to enable output caching on all ashx files in my site. I'm trying to keep the server from generating the file on each request - NOT trying to tell the browser to cache the file.
I've distilled my ashx file down to this simple code:
public class DefaultStyles : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/css";
StringBuilder styleSheet = new StringBuilder();
styleSheet.AppendLine(string.Format("/* Generated: {0}, {1} */", DateTime.Now.ToShortDateString(), DateTime.Now.ToLongTimeString()));
context.Response.Write(styleSheet.ToString());
}
}
And in my web.config file, i have this:
<system.webserver>
<caching enabled="true">
<profiles>
<add extension=".ashx" policy="CacheForTimePeriod" duration="00:01:00" />
</profiles>
</caching>
</system.webserver>
Still, every request i make to the ashx file generates a new version with the current date and time in it.
What am i doing wrong?
Thanks.
Maybe this will help?
http://objectmix.com/dotnet/393333-output-caching-custom-http-handler.html
It would seem to suggest that since you're not using the normal page handler, the output caching module isn't invoked.
Simon
I was actually doing everything right, just not testing in the right environment. Once i deployed the simple example above on our IIS 7 server, it worked as expected with the code above. It should be noted that this DID NOT work on our IIS 6 server. I had not realized that this was a new feature only available in IIS 7

Asp .net mvc 2 forms authentication not working on iis 6. Need helps determining correct routes

I'm trying to setup Forms Authentication in an asp.net mvc 2 application that will be hosted on IIS 6. There's an issue somewhere in my routing, but I can't pinpoint exactly where it is.
Here is the route entries I'm using to route the mvc requests through the aspx processing on IIS 6. These may or may not be the "right" way, but they do work on the server at current.
routes.MapRoute(
"Default",
"{controller}.aspx/{action}/{id}",
new { action = "LogOn", id = "" }
);
routes.MapRoute(
"Root",
"",
new { controller = "Main", action = "LogOn", id = "" }
);
I've put the [Authorize] attribute on my Main controller.
In my web.config I have:
<authentication mode="Forms">
<forms loginUrl="~/Main.aspx/LogOn" timeout="2880"/>
</authentication>
When the application starts, a blank page loads. The page is quite literally blank. I haven't found a way to amend the loginUrl to actually execute the LogOn action & View for my Main controller.
Edited
Just as an fyi, I've setup my routing based on this article so that the mvc routing can work on IIS 6.
http://www.asp.net/mvc/tutorials/using-asp-net-mvc-with-different-versions-of-iis-cs
I'm guessing the problem here is that the windows form authentication settings aren't syncing with the routes setup so the app can run on IIS 6 via the aspx extension.
Anyone have thoughts on how I could fix this?
Edit 2
Tried adding the following route:
routes.MapRoute(
"Login",
"Login",
new { controller = "Main", action = "LogOn" }
);
Amended the web.config to:
<authentication mode="Forms">
<forms loginUrl="~/Login" timeout="2880"/>
</authentication>
The result is the same white screen as I originally got. It seems like the page doesn't get processed at all. Viewing the source from page generated shows absolutely nothing....no markup...no html declaration....just nothing.
EDIT 3
It seems that I can't seem to get the correct routing configured with the default forms authentication via the web.config. To circumvent this, I've created my own Authorize attribute class. At current, I only care that the user has logged into the system. To accomodate this, I moved the LogOn & LogOff actions to an Account controller. I've remapped the root path to point to this controller. In my custom Authorize attribute, I check to see if the user is logged in and redirect them back to the LogOn page if they aren't. Here is the code:
routes.MapRoute(
"Root",
"",
new { controller = "Account", action = "LogOn", id = "" }
);
And here's the code for the RequireLoginAttribute class I derrived.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class RequireLoginAttribute : AuthorizeAttribute, IAuthorizationFilter
{
#region IAuthorizationFilter Members
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (!filterContext.HttpContext.Request.IsAuthenticated)
{
//This didn't work...it would try routing to urls like
//http://localhost:1524/Main.aspx/Account.aspx/Logon
//new RedirectResult("Account.aspx/Logon");
//This seems sloppy to me somehow, but it works.
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Account", action = "LogOn" }));
}
}
#endregion
}
Now, I can just apply the [RequireLogin] attribute to the Main controller and it ensures the user must be authenticated.
For the curious, and completeness of this scenerio, I am using the following code in the LogOn action (repository isn't ready yet so things are hard coded):
public ActionResult LogOn(LogOnModel login, String returnUrl)
{
if (ModelState.IsValid)
{
FormsAuthentication.SetAuthCookie(login.UserName, false);
return Redirect(returnUrl ?? Url.Action("NextPage", "Main"));
}
else
{
return View(login);
}
}
The returnUrl is a throwback to the Windows Forms authentication. Since I can't seem to get that working here, the parameter will always be null.
Please, critique this if you see specific areas that need improvement. I'm reading what I can and trying to do things right, so all input is greatly appreciated. Thanks!
If you need the .aspx for the Default Root then why don't you need it for the login route ?
You could do a couple of things then
Actually create a ASP.NET page called Login.aspx and put it in the root of the folder (Authentication will work for your mvc pages as well)
Change your login route to say
routes.MapRoute("Login","Login.aspx",new { controller = "Main", action = "LogOn" });
You should also take a look at to see what route your actually hitting at any time.
http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx
Remember that the order you write your routes in Global matters. It stops checking when it finds one that works so your catch all should be last.
The details I posted in EDIT 3 summarize the solution to this issue. I appreciate all of your input into this question, but I've resolved it. I would have liked to have gotten the "out of the box" forms authentication working, but this solution serves well enough. If we move to IIS 7, I think all of this will become moot anyhow.
Thanks again for your help guys.

Categories

Resources