Trying to access Index of MVC controller, Exception - c#

So.. i have a MVC webpage. I have defined a Controller
public class NinjaController : Controller
{
// GET: Ninja
public ActionResult Index()
{
return View();
}
}
The my routes are set up like this:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute("Default", "{controller}/{action}/{id}", new
{
controller = "Login",
action = "Login",
id = UrlParameter.Optional
});
}
}
And i have a Folder in the Views folder that is named Ninja and an Index.cshtml file in there that looks like this:
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
Very simple... This is a business application with lots of different settings and configurations... If i do the exact same thing in a new solution it works just fine...
However when i try to access (http://localhost:1235/Ninja) view i get the following error:
{"A public action method 'Login' was not found on controller 'Stimline.Xplorer.Web.Controllers.NinjaController'."}
To me it seems like there should be something confusing the routing function.. but i have no idea where this logic could be placed... anyone have any suggestions?
Interesting fact: If i change the name of the method from Index() to OhYea() and create a corresponding view everything works as expected....

Your routing configuration is saying that pretty much all routes should go to Login which is why your Ninja route doesn't work.
The recommended way of enforcing authentication against a particular route is to use the AuthorizeAttribute. To summarise, keep your default route
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Ninja", action = "Index", id = UrlParameter.Optional }
);
But restrict your NinjaController to authorized users only
[Authorize]
public class NinjaController : Controller
{
...
}

Related

How to Create URL friendly route and remove index

I know how to create a URL friendly route and i also know how to remove index. But I'm wondering how do I combine the two together?
Using this tutorial https://www.jerriepelser.com/blog/generate-seo-friendly-urls-aspnet-mvc/ I was able to add the following code to allow for url friendly routes.
routes.Add("ProductDetails", new SeoFriendlyRoute("drink/{id}",
new RouteValueDictionary(new { controller = "Drink", action = "Index" }),
new MvcRouteHandler()));
So instead of my url being test.com/index/drink/1 it now becomes test.com/index/drink/coke
The next set of code I have is to remove the index from the url.
routes.MapRoute("DrinkRoute",
"drink/{id}",
new { controller = "Drink", action = "Index" });
This will succesfully convert test.com/index/drink/1 to test.com/drink/1
May I ask how do I combine the two together so that I can have a route that will lead me to the correct controller action and display test.com/drink/coke
RouteConfig
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
You can also achieve the same using attribute routing which would provide more control of the desired routes.
Reference Attribute Routing in ASP.NET MVC 5
First you would need to enable attribute routing by calling routes.MapMvcAttributeRoutes(); in your RouteConfig. Make sure it is registered before convention-based routes.
public class RouteConfig {
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//Attribute routes
routes.MapMvcAttributeRoutes();
//Default convention-based routes
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
With attribute routing enabled you can specify your routes by annotating your actions and controllers.
[RoutePrefix("drink")]
public class DrinkController : Controller {
[HttpGet]
[Route("{name}")] // GET drink/coke
public ActionResult Index(string name) {
//...use name to get model
return View();
}
//..
}
The above DrinkController.Index action is now mapped to GET drink/coke assuming test.com is the host of the controller as shown in your example.
Any controllers or actions not annotated by routing attributes will default back to the convention based routes (if any) registered in the routing table.
This means that you can have a mix of convention-based and attribute-based routes defined for your controllers.
Note however that once you use the attribute routes on a controller that you will have to use it on all its public actions.
If I understand you correctly, you can achieve desired behavior with RouteConfig.cs:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "DrinkRoute",
url: "drink/{id}",
defaults: new { controller = "Drink", action = "Index" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
In that case the url test.com/drink/coke will be hit with the controller DrinkController.cs and the action method Index. Id will be coke. Source code of this controller:
public class DrinkController : Controller
{
public ActionResult Index(string id)
{
return View();
}
}
You can remove the SEO Routes and give your action or controller full control:
public class DrinkssController : Controller
{
[Route("drink/{drinkName}")]
public ActionResult Index(string drinkName)
{
var model = _drinks.First(x => x.name == drinkName);
return View(model);
}
}

How to Create a dynamic Controller to handle many static Views in ASP.NET MVC?

I have a bunch of mostly-static pages (about 40),
like: order-form01.html, order-form02.html, orderform03.html etc..
Should each of them have its own Controller/Action, or is that possible to have one dynamic Controller/Action for all of them?
My Url should look like this: http://MyProject/GlobalController/IndividualView and for the above example: http://MyProject/OrderForm/order-form01, http://MyProject/OrderForm/order-form02 etc..
Thanks in advance.
Yes it's very easy AND you don't need a switch statement or any other redundant logic.
public class MyController
{
public ActionResult Page(string file)
{
return View(file);
}
}
The magic is in the Route Map:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// New MapRoute for your 40+ files..
routes.MapRoute(
"OrdeForm",
"OrderForm/{file}",
new { controller = "MyController", action = "Page", {file} = "" }
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }
);
}
Additionally:
I pass the View name in the query string.
Is not required, but is supported. The following urls will work:
// Url Parameters
http://MyProject/OrderForm/order-form01
http://MyProject/OrderForm/order-form02
// Querystring Parameters
http://MyProject/OrderForm?file=order-form01
http://MyProject/OrderForm?file=order-form02
The only catch is that you need to rename your html files to cshtml and place them in the correct directory for the ViewEngine to find.
#Erik, I also bit of new to mvc . Could you please explain your route map as of how is it possible with default raute again and again
Routes are broken down into 3 values:
Controller
Action
Parameter(s)
At a bare minimum, the controller and action are required. Where the values come from is not dependent on the Url. For example, in the following Url and Map Route...
// Url
http://MyProject/
// MapRoute
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = "" }
);
// Controller named "Home" matches the default in the above route
// Method named "Index" matches the default in the above route
public class HomeController {
public ActionResult Index() {
return new EmptyResult();
}
}
... everything still works because we provided a default value for the controller and action.
Ok let's break down the URL you want:
http://MyProject/OrderForm/order-form01
http://MyProject/OrderForm/order-form02
http://MyProject/<identifier>/{parameter}
You have one identifier that tells me route (OrderForm) and one changing value that because it changes and you want one value, should be a parameter.
http://MyProject/<identifier>/{file}
The name of the parameter makes no difference as long as it matches the signature of the controller method:
http://MyProject/{Controller}/{file}
public class HomeController {
public ActionResult Index(string file) {
return new EmptyResult();
}
}
or
http://MyProject/{Controller}/{einstein}
public class HomeController {
public ActionResult Index(string einstein) {
return new EmptyResult();
}
}
I named the parameter file, because it tells me it's the parameter is a name of a file, whereas the name einstein has no inherent description so is a terrible name for a variable.
http://MyProject/{Controller}/{file}
// MapRoute
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = "" }
);
// Controller named "Home" matches the default in the above route
// Method named "Index" matches the default in the above route
public class HomeController {
public ActionResult Index() {
return new EmptyResult();
}
}
Now we only want this route to run when the identifier is OrderForm so we don't allow that to be a value, we hard code it.
url: "OrderForm/...
Next we have a value that keeps changing, so we to add url parameter:
url: "OrderForm/{file}"
Now we have an issue because we aren't allowing MVC to parse values from the url to populate Controller nor Action so we must supply them.
routes.MapRoute(
name: "",
url: "OrderForm/{file}",
defaults: new { controller = "Home", action = "Index", file = "" }
);
Here we've mapped the url http://MyProject/OrderForm/{file} to:
public class HomeController {
public ActionResult Index(string file) {
return new EmptyResult();
}
}
Now I would choose to to update the defaults to something more specific and descriptive:
routes.MapRoute(
name: "",
url: "OrderForm/{file}",
defaults: new { controller = "OrderForm", action = "Index", file = "" }
);
public class OrderFormController {
public ActionResult Index(string file) {
return new EmptyResult();
}
}
Hope that all makes sense.
After the question edited :my solution is, you can have one controller/action and it should call view (cshtml). Your querystring data should be pass to view as of viewbag variable and partial views should be called acording to the viewbag variable. noo need of editing routing table even(if you are willing to pass it as a query string).
//your routeconfig will be
routes.MapRoute(
name: "default",
url: "{controller}/{file}",
defaults: new { controller = "OrderForm", action = "Index", file = "" }
);
//here no need to have 40 routing table one is enough
//your controller/action will be
public class OrderForm
{
public ActionResult Index(string file)
{
ViewBag.Orderform=file
return View(file);
}
}
//view bag variable is accessible in view as well as in javascript
But I would say as best practice, you can modify default routing to access all urls and navigate it to same controller/action and let that action to return the view. After that use angular / knockout js to handle client side routing and based on it the partial views should be loaded.(still your url will be different for your 40 pages but noo need to pass it as query string)
//your route table will be
routes.MapRoute(
name: "default",
url: "{controller}/{file}",
defaults: new { controller = "OrderForm", action = "Index"}
);
//your controller will be
public class OrderForm
{
public ActionResult Index()
{
return View(file);
}
Navigation should be handled by client side routing

How do I get ASP.NET to route a controller properly?

I have this in my controller:
public ActionResult Details(int? id)
{
if(id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Sales saleRecord = new Sales();
var result = saleRecord.GetSalesOrderHeader((int)id);
return View(result);
}
However if I browse to /ControllerName/Details/5 I get this error:
"Server Error in '/' Application. - The view 'details' or its master was not found or no view engine supports the searched locations."
The strange thing is that if I use ASP.NET Scaffolding to generate a view, the Details part of that works fine. It's basically the same code I have above as well.
Here's my RouteConfig.cs, if that's relevant:
public class RouteConfig
{
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 }
);
}
}
So why is that the scaffolding controller works fine, without having anything specific added to RouteConfig, yet my controller Details method is not working?
There should be more detail in error that what locations have been searched. Did you put break point in controller and checked if its being hit?
try
return View((object)result);
instead of
return View(result)
cause its calling overload View(string viewName)
If this doesn't work, try to specify viewName explicitly like this:
return View("ViewName", name);
Additionally, check your folder structure. MVC looks for views (like Index) under the views folder but they also have to be under a folder named after their controller (except partial views).

How to specify route options to specific controllers in ASP.NET MVC 5

I would like to suppress the controller from the route, and it worked fine using this:
routes.MapRoute(
name: "HomePages",
url: "{action}",
defaults: new { controller = "Home", action = "Index" }
);
The problem is when doing the same for a different controller like "Account", the first option only will take effect :
routes.MapRoute(
name: "LoginRoute",
url: "{action}",
defaults: new { controller = "Account", action = "Login" }
);
My objective is to hide the controller from the route, so i can directly access mysite.com/login and mysite.com/index, how to achieve that when login is under Account controller and index is under Home controller?
How to specify the second option for the Account actions, and keep the first for the Home actions?
Have you thought about using the Routing attributes e.g:
[Route("{getId:int}")]
public ActionResult Show(int getId) { ... }
you can use this in conjunction with the old way of routing. You do need to explicitly set this functionality in your config:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
}
}
I have found the routing Attributes makes it very easy to set good routes on my controller methods. This also bleeds into web api and RESTFul stuff as well.

rout registration breaks when I change the url in global.asax

The following rout registration works for my asp.net MVC application
routes.MapRoute("TrackingChannels", "TrackingChannels/{action}",
new { controller = "TrackingChannels", action = "Index" });
When I change it to catch this url,
I get resource not found error
for localhost:85\dis\TrackingChannels
routes.MapRoute("TrackingChannels", "Dis/TrackingChannels/{action}",
new { controller = "TrackingChannels", action = "Index" });
How can I fix this?
Alright, I need to go out so I'll post this now as I don't know how long I'll be.
I setup a default MVC 3 project and changed the routing to match your case.
Global.asax:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"TrackingChannels",
"Dis/TrackingChannels/{action}",
new { controller = "TrackingChannels", action = "Index" }
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Added a TrackingChannelsController:
public class TrackingChannelsController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Test()
{
return View();
}
}
I deliberately added the Test action to see if /dis/trackingchannels/{action} would also work. Then I added a couple of views which resulted in the following project structure:
Finally, here's the results of specifying the URLs in the browser:
First with /dis/trackingchannels:
Second with /dis/trackingchannels/test:
The only thing I can say without seeing your project is to double check the URL is matching the correct route. To do that you can use Phil Haack's RouteDebugger.

Categories