How do I make a scaffolded page the first page - asp.net-mvc

So I'm following the get started tutorial on ASP.NET . So far so good, however going to /controllerName is quite tedious. Is there a way how I can go to that index page on start up of the project? I couldn't find it in the walkthrough or any documentation. I'm using version 6.0 . I'm sorry for this basic question.

.NET MVC has built in defaults that can be overriden.
The default start page which will be routed from the root / is the Index action on the home controller:
public class HomeController :
{
public IActionResult Index()
{
// ...
}
}
Sticking to these defaults is a good idea so other developers will find it easier to make sense of your project.
But you can override the defaults in .NET 5.0 if you wish in the Startup.cs Configure method:
app.UseEndpoints(routes =>
{
routes.MapControllerRoute(
name: "default",
pattern: "{controller=MyDefaultController}/{action=MyDefaultActionMethod}/{id?}");
});
}

You can change the desired starting page from Route config. It's in
App_Start>RouteConfig
route config
You can change it controller name and index page as you want.
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controllerName}/{actionName}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}

Related

How can I get my asp.net MVC routing to use a default action within a sub-folder?

I have an ASP.Net MVC app where I need to place a certain section of code in a sub-folder named web.
I would like for the user to be able to simply type "http://www.mywebsite.com/web/mycontroller" and have it default to the action of index.
However, I can't seem to figure out how to set up my routing to default the action. From what I can tell, it's trying to use the controller = web, action = mycontroller.
My route code looks like this:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"web", "web/{controller}/{action}",
new { action = "Index" });
}
The request works fine as long as I include the /index on the end of my URL, but it doesn't seem to want to use the action = "Index" default if I exclude it.
How can I accomplish this?
Change your code as follows:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "web",
url: "web/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
I ended up using Areas, and this has fixed my problem.

Regarding Route.config file and attribute routing ASP.Net MVC

We know route is register in route.config file like below
routes.MapRoute(
name: "ProductPage",
url: "{productId}/{productTitle}",
defaults: new { controller = "Products", action = "Show" },
constraints: new { productId = "\\d+" }
);
Can we delete routing related code from route config file and implement attribute routing instead?
See this
[Route("{productId:int}/{productTitle}")]
public ActionResult Show(int productId) { ... }
Can we use the above attribute routing instead?
Can we delete all routing related code from route config file, so my route config would look like?
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
}
}
Please help me to have control over this routing issue. Thanks
You certainly can, but it's better to keep one default route in RouteConfig and add decorate other action methods with route attributes.

ASP.Net MVC Redirect Specific Routes to External Site

I have an nicely functioning ASP.Net MVC site using the simple standard routing scheme:
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }
);
My client would like to redirect the static pages to a secondary site, so that they can edit them, template-style, at will. The pages that actually do something will remain on the original site.
What I need to do is set up routes for my functional views/controller-actions and redirect the remaining urls to the external site regardless of whether or not the specified url has a matching controller/action. I don't want to mess with the existing code, but use routing to execute some of the pages and redirect from others.
For example:
mysite.com/sponsors/signup would be executed
mysite.com/sponsors/information would be redirected
Even though the sponsors controller contains actions for both signup and information and there are existing views for both signup and information.
So far, I have been unable to wrap my head around a way to do this.
Any ideas?
You can use attribute routing to make it easier.
Your RouteConfig will look like below:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes(); // enable attribute routing
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }
);
}
}
Then you can add an action like below:
public class SponsorsController : Controller
{
[Route("sponsors/information")]
public ActionResult RedirectInformation()
{
return RedirectPermanent("http://yoururl.com");
}
}
EDIT ONE
If you don't want to use attribute routing, you are still going to need the action but your RouteConfig will look like below:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//The order is important here
routes.MapRoute(
name: "redirectRoute",
url: "sponsors/information",
defaults: new { controller = "Home", action = "RedirectToInformation"}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
In routing like this, if the match is found the rest of the routes are ignored. So, you'd want to put most specific route on top and most general in the bottom
EDIT TWO (based on the comment)
You can put a simple appsettings in Web.config like below:
<appSettings>
<add key="UseAttributeRouting" value="true" />
</appSettings>
Then in RegisterRoutes you can read it like below and make the decision.
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
if (Convert.ToBoolean(ConfigurationManager.AppSettings["UseAttributeRouting"]))
{
routes.MapMvcAttributeRoutes();
}
else
{
routes.MapRoute(
name: "redirectRoute",
url: "sponsors/information",
defaults: new {controller = "Home", action = "RedirectToInformation"}
);
}
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
The browser sometimes caches these redirects, so you may want to recommend clearing browser caches if you change these settings. Check this superuser post for clearing the cache for Chrome.
You have two options
i) This is perfect use case to write a custom mvchandler that is instatiated by a custom IRoutehandler. You can follow this example.
http://www.eworldui.net/blog/post/2008/04/aspnet-mvc---legacy-url-routing.aspx.
ii) You can write HttpHandler for these matching paths you can redirect them to the other site.
Step 1: add this to RouteConfig.cs
routes.IgnoreRoute("yourwebpage.aspx");
Step 2: create new file at root of website called "yourwebpage.aspx"
Step3: Inside yourwebpage.aspx put:
<%
Response.RedirectPermanent("http://yourwebsite.com");
%>
It is pretty simple.
Create an Action
public ActionResult ext(string s)
{
return Redirect(s);
}
And in Routeconfig file add
routes.MapRoute(name: "Default17", url: "routeyouwant", defaults: new { controller = "Home", action = "ext", s = "http://externalurl.com" });

Adding new pages to MVC 3 project results in "Resource not found" error

I have an existing MVC 3 project I've been working on for a while. Today I decided to add a new page. I added a new view, hooked it up with an actionresult on an existing controller but no dice. I get a 404. I thought maybe something was wonky with the view so I did a response.write in the controller (to take the view out of the equation). No dice. I tried creating a new controller. Same thing. I tried moving an existing page. Same thing. All existing pages work, but I can't add new ones or move existing ones. My keyboard is covered in hair. Please help.
My global.asax:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
routes.MapRoute(
"Home",
"",
new { controller = "Home", action = "Index" }
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
The view I'm trying to add is /Views/Restaurants/Nearby.
The controller is /Controllers/RestaurantsController and the ActionResult is:
public ActionResult Nearby()
{
return View();
}
Start by removing the following useless line from your route definitions:
routes.MapRoute(
"Home",
"",
new { controller = "Home", action = "Index" }
);
so that you only have the default route setup:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Now in order to access your new controller action you would navigate to /Restaurants/Nearby. This will render the Nearby action on the Restaurants controller:
public class RestaurantsController: Controller
{
public ActionResult Nearby()
{
return View();
}
}
which obviously would execute the ~/Views/Restaurants/Nearby.cshtml view.
I know this is an old thread but I have found many many 'Resource Not Found' solutions which did not help me. After some time I worked out my issue. Hopefully it will help someone else.
The problem was that I had been messing about with deploying my application, so my project happened to be set to a 'Release' configuration. I had also altered the release configuration to compile to a different folder.
So I think when I was hitting 'Run' in the toolbar, it was picking up an older DLL and running from that.
I only spent three hours on this so I'm happy.
You could try adding the Route Debugger NuGet package IIRC,
Get-Package routedebugger
If needed, change your web.config entry to activate the route debugger for all requests:
<add key="RouteDebugger:Enabled" value="true" />
Then you should build and run your project, and navigate to /Restaurants/Nearby/. The resulting diagnostics should tell you where your routing issue (if any) lies. If you are still having trouble, edit your post with the route debugging info and we'll see what we can do!

ASP.NET MVC Area not picking up the correct route

I am in the process of debugging a routing issue on my MVC 3 application and I am using Phil Hacks routing debugger.
I cannot seem to work out where the route highlighted in yellow below is originating. Each time I run my application with the following request
http://www.mywebsite.com/auth/login?ReturnUrl=/
this route comes first and then gives me a 404 error as I do not have an index action. As you can see I have set my default routes to use the Login action method but still this route persists.
I have the following route configurations:
AuthAreaRegistration
public class AuthAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Auth";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"login",
"auth/login/{*returnPath}",
new { controller = "Auth", action = "LogIn", id = UrlParameter.Optional }
);
context.MapRoute(
"Auth_default",
"Auth/{controller}/{action}/{id}",
new { controller = "Auth", action = "LogIn", id = "" }
);
}
}
Global.asax (Using T4 MVC Templates)
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Home",
"{controller}/{action}/{id}",
MVC.Home.Index(), new { id = UrlParameter.Optional },
new string[] { "MyNamespace.WebUI.Controllers" }
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
MVC.Home.Index(), new { id = UrlParameter.Optional },
new string[] { "MyNamespace.WebUI.Controllers" }
);
}
I don’t like to answer my own question but after a day of trying to solve this problem I thought I would post the answer in case anyone else has the same issue.
It turns out that my application was holding onto old routes and populating them into my route collection. I deleted all the files in my bin folder and rebuilt my solution and everything worked as it should.
I have answered this question in a little more detail here:
Does ASP.NET MVC create default routes for areas
I think the problem is in the fact that you have an area called Auth and a controller called Auth outside of the areas.
MVC will try to match your url against Auth area first but you actually want it to hit your auth controller outside an area.
The best way to solve it imho is to avoid a ambiguous names of controllers/areas.

Resources