Every request to be routed to a single controller - MVC - asp.net

I was asked this question in an interview.
Can someone please let me know the answer for this.
"I have an MVC application and I want all the requests to be targeted to a single controller, which would then decide the actual controller to which the request to be sent to and that controller should actually handle the request. How do I achieve this?"
Thanks,
Vijendra

This seems like a bad idea, but if you wanted to do something like that you would do it like this in RouteConfig.cs
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{action}/{id}",
defaults: new {
controller = "Base",
action = "Index",
id = UrlParameter.Optional }
);
}
}
And you would have a matching BaseController.cs

Related

Some Controllers not going to default Index action

I have a MVC project. I added a few controllers; over time edited in some code some controllers. Might have done something where I landed up in the following problem and now I do not know how to fix it.
Now http://server/Controller1 correctly executes Index action. But http://server/Controller2 does NOT execute the Index action; instead I get "The Web server is configured to not list the contents of this directory." http://server/Controller2/Index works as expected.
I have gone through similar questions. As you can see Controller1/ routing is happening properly. So it is not IIS config. Controller2 has index() function; it is not route config issue as well; I have not added any specific route for Controller1 or Controller2. The route is basically the default route
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
It sounds like you may have a folder in your website called Controller2, as the webserver is trying to list its contents

Trying to display Custom View in MVC app but it says requested URL not found

I am new to azure, MVC and also ASP.NET. I am writing MVC Cloud service with ASP.NET web role. Please help me with this problem
When I create the application there are default views but I wanted to see my view so I set my view as start page. I also changed the values in RegisterRoutes method
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "User", action = "AddUser", id = UrlParameter.Optional }
);
}
When I run the app, it gives HTTP 404 error because it could not find request URL : /Views/User/AddUser.cshtml
In MVC you don't put the view in the URL to get it rendered.
This won't work: /Views/User/AddUser.cshtml
As you've correctly put in your question the default route is {controller}/{action}/{id} with id being optional.
So assuming that User is your controller, i.e. you have a class called UserController, which looks something like:
namespace My.Controllers
{
public class UserController : Controller
{
which has an action on it called AddUser:
public ActionResult AddUser()
{
// implementation logic
return View();
}
Then the default route will display your view when it processes the URL /User/AddUser
In MVC 5, this looks something like:

Asp.Net WebApi Routing 404. Controller becomes "Api"

I am trying to reach a specific webapi action using: api/error/LogJsError with some formdatacollection. I have an ErrorController like this:
public class ErrorController : ApiController
{
[System.Web.Http.HttpPost]
public void LogJsError(FormDataCollection form)
{
var s = form.Aggregate("Javascript error: message", (current, i) => current + (": " + i.Value));
new Logger(HttpContext.Current).LogException(new Exception(s));
}
}
and the routes are configured like this:
config.Routes.MapHttpRoute(
name: "ApiWithAction",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
In WebApiConfig.Register and
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
inside the RouteConfig.RegisterRoutes
But whatever i do the routecollection returns controller = "Api" which thus results in a 404. What am i doing wrong, why is the api route not uses?
Duuuh...i found the answer right after posting it on: https://msdn.microsoft.com/en-us/library/cc668201%28v=vs.140%29.aspx
Note this: "To avoid having the wrong handler handle a request, you must consider all these conditions when you define routes. The order in which Route objects appear in the Routes collection is significant. Route matching is tried from the first route to the last route in the collection. When a match occurs, no more routes are evaluated. In general, add routes to the Routes property in order from the most specific route definitions to least specific ones."
My MVC route (eg: {controller}/{action}/{id}) was added to the routecollection before the (more specific) WebApi route (eg: api/{controller}/{action}/{id}). So instead of using:
RouteConfig.RegisterRoutes(RouteTable.Routes);
GlobalConfiguration.Configure(WebApiConfig.Register);
In Application_Start(), use:
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);

Running an action method on every view

I want to show the version info of the current project on every page.
The way I do it in the moment is like this:
Inside the Index method of my homecontroller:
ViewBag.Version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
Inside the _layout.cshtml(masterpage):
#ViewBag.Version
The Problem here is, it will only displayed once, but I want to display the Version on every page/view.
This is my routing configuration:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Do I have to change something here ?
Ty for helping
Why not just call
#System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
on the _Layout.cshtml view?
MVC has a different launch context and a work around is needed to text the version:
#typeof(HomeController).Assembly.GetName().Version
HomeController could be replaced with any other type in the assembly the MVC application assembly. See this question for more info.
Just put this in the Layout.
<label>#System.Reflection.Assembly.GetExecutingAssembly().GetName().Version</label>

default page issue with 4.0 ASP.NET and MVC mixed mode website

I am converting a classic ASP.NET 4.0 site to also use MVC. Over time I am migrating the ASP.NET code to MVC, but during the transition both technologies will be in use.
If I navigate to the default page (ie, http://mywebsite.com/), then MVC routing is taking over and returning the following message.
This request has been blocked because sensitive information could be
disclosed to third party web sites when this is used in a GET request.
To allow GET requests, set JsonRequestBehavior to AllowGet
If I use http://mywebsite.com/default.aspx, then everything works fine.
My route config looks like...
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//ignore aspx pages (web forms take care of these)
routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
Notice I am ignoring .aspx page requests, so these requests get ignored by the MVC pipeline. However, I need 'no page specified' default requests to process default.aspx. How would I change the above code or configure the site/IIS to make this happen?
I removed the default route and now the behavior is as needed.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//ignore aspx pages (web forms take care of these)
routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { id = UrlParameter.Optional }
);
}

Resources