RouteLink Not work in MVC 4 - asp.net-mvc-4

In my application I allow user to redirect to htttps://www.google.co.in from my application.
for that I used RouteLink.I know we can also do it by actionLink.
CODE:
#Html.RouteLink("Google",null,"https","www.google.co.in", null, null, new { #style = "color:red" })
Generated HTML
<a style="color:red" href="https://www.google.co.in/Home/RouteLink">Google</a>
And I also add Routing
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "RouteLink",
url: "Home/RouteLink",
defaults: new { Controller = "Home", action = "RouteLink" });
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id =
UrlParameter.Optional }
);
}
So my Question is why I get anchor tag Like above? and If RouteLink does not allow to redirect to another domain than why It had overloaded method that accept hostname and protocol?

So my Question is why I get anchor tag Like above
Because you specifically tell it so on the 3rd and 4th parameter of RouteLink.
If RouteLink does not allow to redirect to another domain than why It
had overloaded method that accept hostname and protocol?
Because that's not what you use it for. RouteLink and it's sister method ActionLink are used to generate valid (or safe) links within your application.
If you want to link to an outside application/website then just use the anchor tag.

Related

Overriding Controller Routing

I'm using ASP.NET MVC 5 and I'm looking to dynamically choose which controller handles a particular request.
For example, the user might request /ControllerName/ActionName/, but I want to first look and see if in my source I have a controller /CustomCodeDirecotry/ControllerName/ActionName. If I have that controller, then use that to process the request. If I don't then go ahead and use the requested controller.
The key in this is that I don't want the user to know that they were handed off to a different url.
In the end the answer to this question was to provide a namespace when mapping routes. Specifically:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "MvcSite.Special.Controllers" });
I found my answer here

MVC Web API route config - filter controllers in route templates

My WebApiConfig.cs Register method looks like this:
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "ClassroomContentApi",
routeTemplate: "classroomContent/{controller}/{id}",
defaults: new {id = RouteParameter.Optional}
);
// Default
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new {id = RouteParameter.Optional});
MediaTypeHeaderValue appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
}
My Controllers folder in my MVC project is structured like this (these are not the real names of the controllers but that's not important):
Controllers
ClassroomContent
ClassroomController.cs
ClassroomController2.cs
ClassroomController3.cs
SchoolInfo
CampusController.cs
CampusController2.cs
CampusController3.cs
StudentInfo
StudentController.cs
StudentController2.cs
StudentController3.cs
etc...
I want all the controllers in the ClassroomContent folder to use the first route above, and all the other controllers (in any other folders) to use the second route above.
The issue I am having is that the first route above picks up web api actions in controllers outside the ClassroomContent controllers folder, and vice versa.
For example, I can access http://MYHOST/classroomContent/Campus or http://MYHOST/api/Classroom. I want to be able to access the Classroom controller only from http://MYHOST/classroomContent/Classroom and the Campus controller only from http://MYHOST/api/Campus.
I understand that this is "expected behavior" in that nothing is preventing this from the perspective of how my routes are configured. But how do I prevent it?
What I have considered:
Using areas. However, from what I read, they are not supported for Web API (at least not out of the box). I could try to explore the option of trying to implement areas functionality, but it seems like a lot when I am not even sure that they are the right solution.
Defining a separate route for each controller. However, I have many controllers, so this seems very cumbersome.
What would be the best way to approach this problem? Is there any way to do it without trying to implement areas for Web API myself? Ideally I'd be able to somehow "filter" which controllers are valid values for the {controller} parameter of each route template.
RouteConstraints should also work if you prefer not to use attribute routing.
Assuming your controllers are named: ClassRoom1Controller, ClassRoom2Controller etc the following should work (note that you can use regular expressions to configure the constraints so there should be many possibilities to configure this as you like):
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "ClassroomContentApi",
routeTemplate: "classroomContent/{controller}/{id}",
defaults: new {id = RouteParameter.Optional},
constraints: new { controller = "classRoom1|classRoom2|classRoom3" }
);
// Default
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new {id = RouteParameter.Optional},
constraints: new { controller = #"^((?!(classRoom1|classRoom2|classRoom3)).)*$" });
MediaTypeHeaderValue appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
}
This link should help you : http://aspnetwebstack.codeplex.com/wikipage?title=Attribute%20routing%20in%20Web%20API
You can define custom routes at controller level with Web Api 2.

MVC4 - My Custom Route isn't working

So I have a custom route in my MVC4 web app below:
routes.MapRoute(
name: "SecondarySportsCategoryLanding",
url: "sports/{name}/{id}",
defaults: new { controller = "FrontCategoriesController", action = "Sports", name = UrlParameter.Optional, id = UrlParameter.Optional }
);
I have that placed above my default one as well. What's happening is when I go to /sports I get this error:
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: /sports
I have the controller specified, and inside that I have an Action titled Sports with 2 optional parameters (defaulted to nulls). Any ideas?
controller = "FrontCategoriesController" should be controller = "FrontCategories"
Because the framework automatically inserts Controller into the value for you.

How to map URL that does not contain the {controller} to a controller?

I am very familiar with URL routing in Web Forms and have a basic understanding of MVC routing but have ran into a scenario I am not sure how to wire up. I want to map the a URLs that do not contain the {controller} in the URL map to a controller.
I want to map the following URLS to the controller "SectionHomePageController"
Books/{Action}
Cinema{Action}
Collections/{Action}
Games/{Action}
I know the typical way of a route would be {controller}/{action} so I am not really sure how to wire up these URLs to a controller. So how do I wire up these URLs?
Map a route (should be above your regular {controller}/{action}/{id} route so it takes precedence) that has a constraint and defaults to your SectionHomePageController:
routes.MapRoute(
name: "SectionHomePage",
url: "{prefix}/{action}",
constraints: new { prefix = #"(Books|Cinema|Collections|Games)" },
defaults: new { controller = "SectionHomePageController", action = "Index" }
);
Note that you now won't be-able to have a BooksController, CinemaController etc as this route will override the default one.
routes.MapRoute(
"SomeRoute", // Route name
"Collections/SomeAction", // URL with parameters
new { controller = "SectionHomePageController", action = "SomeActionOnController", id = "" } // Parameter defaults
);

MVC2 Routing with WCF ServiceRoute: Html.ActionLink rendering incorrect links!

I have a WCF service that lives side-by-side with an MVC2 web site. I'd like for my URL for the service to look like this:
http://localhost/projdir/Service
The MVC site is in its infancy so it still has all its boilerplate controllers etc.
The following code works at first glance in global.asax:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.Add(new ServiceRoute("Service", new ServiceHostFactory(),
typeof(MyService)));
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index",
id = UrlParameter.Optional } // Parameter defaults
);
}
The service appears just where I described and works as advertised. Great.
However, I just noticed that ordering my code this way changes all of my ActionLink's. For example, the "About" tab on the MVC site now appears like this:
http://localhost/projdir/Service?action=About&controller=Home
This is obviously incorrect (it should be http://localhost/projdir/Home/About/ ).
If I move the ServiceRoute addition below the default MapRoute() call, then I get a missing controller error. (Actually I get a "StructureMapControllerFactory did not return an instance of a controller" error, because I'm wired up with StructureMap, duh, it's not a controller to begin with.)
Interestingly, it only seems to be affecting the output of Html.ActionLink(). I can manually type in http://localhost/projdir/Home/About/ and get to the correct page.
What horribly obvious newbie mistake am I making?
Try moving the Service route after the MVC route. But to avoid the "missing controller" error that you got before, add the MVC route with a Route Constraint. These route constraints can be Regex - basically you'd want your route constraint to be any controller that is not "Service". When a request for "Service" is requested, it will make it fall through and his the WCF Service Route.
I resolved with that:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new { controller = "^(?!api).*" }
);
routes.Add(new ServiceRoute("api", new DataServiceHostFactory(), typeof(dwService)));
I hope this good for you
Another solution is to inherit the ServiceRoute and override the GetVirtualPath method to return null as described here
public class AppServiceRoute : ServiceRoute
{
public AppServiceRoute(string routePrefix, ServiceHostFactoryBase serviceHostFactory, Type serviceType)
: base(routePrefix, serviceHostFactory, serviceType)
{
}
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
{
return null;
}
}
This way, reverse route mapping never select this route for any Action. Works like a charm