Make an MVC controller the default in WebAPI project - c#

I have created my first WebAPI project to learn, which had an index.html page in the root of the project. I set that page as Startup. All working fine. But, I want to use an MVC controller to call the View instead.
So I created a new MVC controller in my Controller folder called "DefaultController". In it, there's a method:
public ActionResult Index()
{
return View();
}
I created a View folder, and off that, a Default folder, in which, I created an Index.cshtml file.
When I start the project, it calls my old index.html. So, I changed the startup to be the index.cshtml, which is wrong - know. MVC calls a controller method. So, I'm trying to work out - how do I call the controller method in my DefaultController?
I think I need to change my routes?
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { action = "Index", id = UrlParameter.Optional }
);
}
My plan is to use cshtml pages (instead of html pages) to make use of layouts and allow controllers to initiate the views. Each view will the use an api call back to my WebApi controllers to do the data handling.
Does that seem like a good way to handle my WebAPI/KnockoutJs project?
I just need to know how to get the controller to be the default.
When removing the index.html page, I get the error:
HTTP Error 403.14 - Forbidden The Web server is configured to not list
the contents of this directory.

I think you need to add the controller name to the defaults object as in:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional }
);
}

You need to register both WebAPI routes and MVC routes:
All this should be done in Application_Start method in Global.asax.cs file:
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
GlobalConfiguration.Configure(WebApiConfig.Register) is used to configure WebApi (and register api related routes)():
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
RouteConfig.RegisterRoutes(RouteTable.Routes); is used to register MVC routes:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional }
);
}
You also need verify that the DefaultController that you created is MVC controller (inherits from System.Web.Mvc.Controller) and not WebAPI controller

According to my experience, when you want to call the index.cshtml, in the route config you have to define the controller like this in the RouteConfig.cs:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
The controller supposed to be "Home", and the Action is "Index". But, this maproute is for default one. How about if you want to add another one?
routes.MapRoute(
"Article",
"articles",
new { controller = "News", action = "ArticleList" }
);
You can write freely as shown above where "Articles" is the name of maproute and the "articles" is the url. And it would become like this (http://www.domain.com/articles) if you compile controller News and Action ArticleList. And "..../articles" is something you replace (No need define controller or action) and you don't need to open www.domain.com/News/ArticleList it's enough to go to url www.domain.com/articles and the maproute would be automaticaly route to controller news and action articlelist.
That's only my point of view about how maproute works.
CMIIW :)

Related

ASP.NET MVC routing add special convention mysitye/string

I am new to ASP.NET MVC. I have a web page with default routing:
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 }
);
}
I have been working on developing an URL shortener that creates 5 character strings in base 32 (A-Z 0-9). My idea is to have the default routing in ASP.NET MVC and add a special case for
// this is the random code generated by my application
www.mypage.com/ASD12
How can I add this exception to my routing and always make URLs (mypage.test/code) land on a specific controller action?
public class CodeController : Controller
{
public async Task<ActionResult> Index(string code)
{
//do things here
}
}
Thank you very much
After searching more,
routes.MapRoute(
name: "specialConvention",
url: "{id}",
defaults: new { controller = "code", action = "Index" }
);
That is the code I was looking for.

Implementing Attribute Routing

I'm trying to get a handle on attribute routing in MVC.
Initially, the routing for my sitemap controller was as follows:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "SitemapXml",
url: "sitemap.xml",
defaults: new { controller = "Sitemap", action = "Index" }
// Additional mappings...
}
}
That works fine. But then I tried commenting out the SitemapXml routing above and instead adding an attribute in my controller.
// GET: Sitemap
[Route("sitemap.xml")]
public ActionResult Index()
{
// Generate sitemap
}
I also added the following line at the end of RegisterRoutes:
routes.MapMvcAttributeRoutes();
But now when I navigate to domain.com/sitemap.xml, I get a page not found error.
Questions:
What steps am I missing to get my routing attribute to work?
Since mappings can now be specified in two places (as attributes or set directly in the RouteCollection), what happens when those two places contradict each other?
if you remove the extension .xml , your attribute routing will work perfectly. And its better to use the extension related code in action method.
Also make sure your route config looke like (routes.MapMvcAttributeRoutes(); should exist before default route)
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Account", action = "Login", id = UrlParameter.Optional }
);

How to use MVC route in ASP.NET WebAPI project

I have a web API and i want to add a few asp.net pages to manage aspects of the API.
In the WebApiConfig.cs file i have a couple of routes, with the following being used as my catch all route for the API.
config.Routes.MapHttpRoute(name: "CatchAll",routeTemplate: "{controller}/{action}/{id}",defaults: new { id = RouteParameter.Optional });
I want to add a new section that is prefixed by /control to push to the asp.net side of things. To do this i have added the following to RouteConfig.cs
routes.MapRoute(
name: "Default",
url: "control/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
I have then added a standard controller that i will use to manage things.
public class ManageController : Controller
{
public ActionResult Index()
{
return Content("Works");
}
}
When i visit /control/manage in the browser i get the following error.
No type was found that matches the controller named 'control'
It looks like the route is being completely bypassed or at best, the catch all from the api route is catching it and giving it priority. IS there a way i can make the request catch this route without having to create a separate project?
The order of registration is matter
You need to register
public class RouteConfig {
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "DefaultMVC",
url: "control/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
//..other routes.
}
}
in the RouteConfig.cs before
config.Routes.MapHttpRoute(name: "CatchAll",routeTemplate: "{controller}/{action}/{id}",defaults: new { id = RouteParameter.Optional });
in the WebApiConfig.cs file.
What happens in your case is that the /control/manage url is handled by CatchAll route thus mapping control to a controller and manage to an action
In order to do that register them in Global.asax in the following order:
RouteConfig.RegisterRoutes(RouteTable.Routes);
GlobalConfiguration.Configure(WebApiConfig.Register);

How do I set up my Routing for my MVC Page?

Greetings New to MVC ...
I am creating my first MVC Application, and I have created it as follows:
CustomUtilities/Controllers/GCItemRetrievalController.cs
CustomUtilities/Views/GCItemRetrieval/GCRetrieve.cshtml
CustomUtilities/Views/Web.config
I want to pull up "GCRetrieve.cshtml in my browser ... but I keep getting a 404 Error
http://mainsite/CustomUtilities/GCItemRetrieval/GCRetrieve
what am I doing wrong? I created the folders for the controllers, models, and Views in a seperate folder on the main system.
Your controller should look something like this:
public class GCItemRetrievalController : Controller
{
public ActionResult GCRetrieve()
{
return View();
}
}
When you navigate to the following url:
http://mainsite/CustomUtilities/GCItemRetrieval/GCRetrieve
It should find the controller's GCRetrieve method and execute it. The return View() call will look for a .cshtml file named GCRetrieve.cshtml, as that is the name of the method.
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 }
);
}
}
When you create a MVC application a class file named as RouteConfig.cs is created in App_Start directory. It has default routing as
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 }
);
}
}
In the above default routing:
if you want call a view CustomUtilities/Views/GCItemRetrieval/GCRetrieve.cshtml
I think CustomUtilities is your project name then use following
http://mainsite/GCItemRetrieval/GCRetrieve
that is
[domanin]/[controllername]/[actionname]
For default routing detail you can refer to http://www.niceonecode.com/Q-A/DotNet/MVC/routing-in-mvc-4/20190

Configure routes for MVC and API in same project

I just merged an existing API project into another existing MVC project. The API controllers have the same name as the MVC controllers but they're in 2 different namespaces (MyApp.Web.MyController and MyApp.API.MyController, respectively).
Now, I don't really know how to configure the routes so that I can access the API controllers :(
I read this post : Mixing Web Api and ASP.Net MVC Pages in One Project and would like the achieve what #Mike Wasson suggested there, but I don't know how to configure the routes.
This is what I currently have in RouteConfig.cs:
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 }
);
}
}
It looks like you already have it working, but should you ever wish to use your API controllers in an area, you can enable it simply by adding an additional route.
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultAreaApi",
routeTemplate: "api/{area}/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
// Application_Start
GlobalConfiguration.Configure(WebApiConfig.Register);
AreaRegistration.RegisterAllAreas();

Categories

Resources