ASP.NET MVC default routh is wrong - c#

I got simple web application with 1 default routing:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Game", action = "Index", id = UrlParameter.Optional }
);
My controller contains the following actions:
public class GameController : Controller
{
public ActionResult Index()
{
// some actions
return View();
}
[HttpPost]
public ActionResult CreateGame(Game game, User user)
{
// some actions
return View("Game");
}
[HttpPost]
public ActionResult JoinGame(User user)
{
// some actions
return View("Game");
}
}
Also under Views/Game folder I got "Index" and "Game" views.
But when I start application from time to time (NOT ALWAYS!) it requests
http://localhost:55815/Game/Game
instead of
http://localhost:55815 or http://localhost:55815/Game/Index

Your application default route is working fine.
The debugger starts url http://localhost:55815/Game/Game because the file Game.cshtml is currently opened in your Visual Studio.
The solution is on your VisualStudio project configuration.
Choose specific page with empty value instead of current/active Page.

Actually,
/Game/Game
and
/Game/Index
are both the same. When you check you default routing file you can see that your main controller is written with predefined controller and action. So the program automatically resolve this url according to that. Mostly try your web application not in visual studio debug but put it under IIS than if you need debugging, debug IIS instance.
Good luck

Related

MVC Resource Can not be found After Publish

I have an MVC Web Application.
When I am running the application from my code, that works fine and I am able to go any pages.
However I publish it on IIS, It gives the error:
The resource cannot be found. Description: HTTP 404. The resource you
are looking for (or one of its dependencies) could have been removed,
had its name changed, or is temporarily unavailable. Please review
the following URL and make sure that it is spelled correctly.
And the URL Changes like below:
http://localhost/IssuerScripting_Web/%23/%23
However the path is
http://localhost/IssuerScripting_Web/UserRoleManagement/User_Management
EDIT: Here is my RouteConfig in below.
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Dashboards", action = "Dashboard_1", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Password",
url: "AdminUserPasswordCreate/PasswordCreate/{id}/",
defaults: new { controller = "AdminUserPasswordCreate", action = "CreatedPassword", id = UrlParameter.Optional }
);
}
And the below is the controller of Dashboard:
public class DashboardsController : BaseController //BaseController
{
public ActionResult Dashboard_1()
{
return View();
}
}
What might be causing this issue?
My default login page is working fine. But this page is like a main page and has all the Menu Items.
I was able to publish it earlier, and was working when I publish. I am not able to figure out the issue.
I will be thankful for any help.
To whom has this problem, After several hours I figured out that Scripts files were not pasting properly when I published it.
I removed the Scripts, Styles, Content folders from my project and added them back.
Then I published and it worked!

Using Areas with RedirectToAction leads to endless loop of redirects

In my ASP.NET Core MVC 2.2 project I'm using areas to facilitate a better structure of classes, views etc. However, I face the following problem when redirecting from one controller to another via RedirectToAction.
I have an area called "Dashboard", a controller called DefaultDashboardController and a HomeController.
The DefaultDashboardController is part of the Dashboard Area. The HomeController does not have an Area assigned.
Within the DefaultDashboardController there is an Index Method which only returns a view.
Now what I'm trying to do is to redirect from the Index Method of the Home Controller to the Index Method of the DefaultDashboardController.
My HomeCntroller looks like this:
public class HomeController
{
[HttpGet]
public IActionResult Index()
{
return RedirectToAction("Index", "DefaultDashboard", new { Area = "Dashboard"});
}
}
My DefaultDashboardController looks like this:
[Area("Dashboard")]
public class DefaultDashboardController
{
[HttpGet]
public IActionResult Index()
{
return View();
}
}
My routing configuration is setup like this in the Startup class:
app.UseMvc(routes =>
{
routes.MapAreaRoute(
name: "AreaDashboard",
areaName: "Dashboard",
template: "{area:exists}/{controller=DefaultDashboard}/{action=Index}/{id?}"
);
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}"
);
});
Now when I call the Index Method of the HomeController, I am always redirected to the very same method (Home/Index) again (causing an endless loop of get / redirect requests).
The only way I was able to resolve this, was by adding an id parameter to the RedirectToAction Call:
return RedirectToAction("Index", "DefaultDashboard", new { Area = "Dashboard", id=1});
However, this is a very ugly, cumbersome workaround for me.
Is RedirectToAction really only supposed to work in this way?
Or is there any fundamental issue on how I want to utlize the Area feature of MVC Core?
Update:
Even though I am still not 100% sure why my initial route causes a short circuit, I cam up with the following solution that works:
app.UseMvc(routes =>
{
routes.MapAreaRoute(
name: "AreaDashboard",
areaName: "Dashboard",
template: "Dashboard/{controller=DefaultDashboard}/{action=Index}/{id?}"
);
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}"
);
});
As you can see, I've added the "Dashboard" path directly to the MapAreaRoute-template.
My assumption is that the {area:exists}- and default-route wereboth evaluated by MVC Core and considered as matching routes. Then the system somehow chose the default route as the target route. With my fixed "Dashboard"-template, this is not the case anymore.
The problem is your default route. The area route should be your default route. It already has the :exists, constraint on that route param, so it will work for non-area routes as well. The routing infrastructure short-circuits, so the default route without the area will be preferred.

ASP.Net MVC #Url.Action() routing to the wrong controller

I'm newbie to MVC. I could integrate MVC 5.2 to my existing web forms Visual Studio 2012 Update 4 project. I created my first controller and all worked as expected. Even I was able to leverage the windows forms authentication from my existing project when accessing the MVC view. But when created my second controller it began messing up.
It is my route mapping:
public static class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.EnableFriendlyUrls();
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
I have two controllers both located in ~/Controllers. My first controller is:
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
//return View();
return Redirect("~/Default.aspx");
}
public ActionResult CloseSession()
{
return Redirect("http://www.yahoo.com");
}
}
The second controller:
public class CajaWebController : Controller
{
//
// GET: /CajaWeb/
public ActionResult Index()
{
return View();
}
public ActionResult CloseSession()
{
return Redirect("http://www.cnn.com");
}
}
I don't know is it relevant to the problem but I'll include how the MVC view is reached. My VS2012 start url is
http://localhost/Fortia/CajaWeb.
Fortia is my app name. Because I declared Web Forms authentication and
<location path="CajaWeb">
<system.web>
<authorization>
<allow roles="Fortia" />
<deny users="*" />
</authorization>
</system.web>
</location>
when starting to debug the old WebForms app authentication mechanism is called, the old WebForms login page invoked and after a successful login finally my CajaWebController, Index() action is called. Before creating CajaWebController it was the HomeController who was called, but I assume MVC now deduces the correct controller is CajaWeb because of the targeted url being
http://localhost/Fortia/CajaWeb.
The invoked view contains the following code:
<a href='#Url.Action("CloseSession", "CajaWeb")'>Close session</a>
The problem is when clicking the generated link the MVC calls HomeController.Index() action despite I explicitly set CajaWebController.CloseSession() in the #Url.Action...
I looked at the generated link and it looks wrong:
<a href='/Fortia/__FriendlyUrls_SwitchView?action=CloseSession&controller=CajaWeb'>
it encoded the parameter separator & into & But anyway I tried handcoding the href as
http://localhost/Fortia/__FriendlyUrls_SwitchView?action=CloseSession&controller=CajaWeb
but the result was the same.
What is wrong?
It would seem the ASP.NET Friendly Urls package you're using is interfering with the urls MVC is generating. The library seems to be meant for WebForms anyway
If it works without, then leave it like that as MVC's urls are already quite SEO-friendly when controller and action names are meaningful to their content.
I think the problem is that the route
http://localhost/Fortia/CajaWeb
doesn't match any routes so it ends up going to the default route specified in RouteConfig. You need to configure a route or create an area in your app called "Fortia".

Server Error in '/' Application in ASP.NET MVC 3 with Razor engine

I just created a new ASP.NET MVC 3 project with the Razor engine. I added a controller to the controller folder, and then at homController.cs I added a view.
The View (index.cshtml) has only this code:
#{
ViewBag.Title = "Home";
}
<h2>Home</h2>
And when I start debugging it shows me this error:
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.225
What's the problem?
Could you check the App_Start/RouteConfig.cs, you must have this code for a controller called homController.cs :
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "hom", action = "Index", id = UrlParameter.Optional }
);
}
I suppose, your first controller name isn't 'Home', so you have to change the default controller name !
Check your routing entries in Application_Start in global.asax since you're using MVC 3. like "Joffrey Kern" suggested, you need to have the routes configured.
also make sure your controller is named "HomeController" and you have a public method called "Index" that returns an ActionResult object.
In ASP .NET MVC 3 your routes are defined in the global.asax
You can find that in the website root.
By default it looks like this:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
This means when you call the website root with no parameters, it uses the default values - in this case home/index.
So you need to make sure you:
have a controller called home
an Action called index that returns an ActionResult
Alternatively you can update the default values in the routes, although if you are just starting out I would not recommend this.
It doesn't have to be your routes ... It could be faulty configurations in web config
If you getting this error I highly recommending you to change your public class name. Give a new name as a "HomeController":
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MyFirstMVC.Controllers
{
public class HomeController : Controller
{
// GET: /First/
public string Index()
{
return "Jay Swaminarayan"; // this string will be display at your run time!!!
}
}
}
THis is ravinder akula
Please find this answer
Right click on your mvc project
Choose "Properties"
Select the "Web" tab
Select "Specific Page"
Assuming you have a controller called HomeController and an action
method called Index, enter "home/index" instead of
home/index.cshtml in to the text box corresponding to the
"Specific Page" radio button.

Asp.net mvc sub-controller

I have to create a site structure like this
/demo/
/demo/admin/create
/demo/admin/edit/id
I can create a DemoController which will contains admin. But how to show create/edit pages? The create/edit pages can be accessible only after user is logged in. Where to put create/edit pages?
If you are certain that you should implement strictly that URL strusture, then maybe "areas" solution would fit you (though not sure, just had a brief view). But I think, that for a small project you could simply make:
separate "admin" controller (that would lead to /demo, /admin/create, /admin/edit/id);
or you could possibly use custom ASP.NET Routing;
As for the authorization, you should look into ASP.NET Web Application Security and User authentication and authorisation in ASP.NET MVC
All you need to do is create a route for /demo/admin, then assign that route to a new controller called DemoAdminController. To make this only accessible to logged in users, you use the Windows Forms authentication system. A sample is provided with the default application generated by MVC.
i agree an area should do the trick or you can add a custom route that points the the controller if you want to lock down the whole section as an admin only section i think areas would be the way to go on this one
Pretty old question, Google landed me here right now.
There is also another way to reach the goal: the Route and RoutePrefix attribute.
Just a small chunk of code for reference.
[RoutePrefix("demo")]
public class DemoController : Controller
{
[Route("")]
public ActionResult Index() { } // default route: /demo
[Route("admin/create")]
public ActionResult Create() { } // /demo/admin/create
[Route("admin/edit/{id}")]
public ActionResult Edit(int id) { } // /demo/admin/edit/5
}
For this to work, the attribute routing must be enabled. In most case is enough to add:
routes.MapMvcAttributeRoutes();
in RouteConfig.cs.
Example:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Dashboard", action = "Index", id = UrlParameter.Optional }
);
}
I think you are looking to use Areas. See docs here:
http://msdn.microsoft.com/en-us/library/ee671793.aspx

Categories

Resources