Set up routes where action name is overwriten in the controller - asp.net-mvc

I need to link cultureRoute Route to various methods in the Controllers decorated with [Route("{urlSlug}")] attribute.
Here is my RouteConfig file
using System.Web.Mvc;
using System.Web.Mvc.Routing.Constraints;
using System.Web.Routing;
namespace Site.Web
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "cultureRoute",
url: "{culture}/{controller}/{urlSlug}",
defaults: new { controller = "Home", urlSlug = UrlParameter.Optional },
constraints: new
{
culture = new RegexRouteConstraint("^[a-z]{2}(?:-[A-Z]{2})?$")
});
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{urlSlug}",
defaults: new { culture = "en-GB", controller = "Home", action = "Index", urlSlug = UrlParameter.Optional }
);
}
}
}
And most of my Controllers have this structure
[RoutePrefix("Branded")]
public class BrandedController : ControllerBase
{
[KenticoCacheFilter]
public async Task<ActionResult> Index()
{
return View("../../Views/Project/Index", viewModel);
}
[Route("{urlSlug}")]
public async Task<ActionResult> Project(string urlSlug)
{
return View("../../Views/Project/Individual", viewModel);
}
// Or
[Route("{urlSlug}")]
public async Task<ActionResult> Article(string urlSlug)
{
return View("../../Views/Project/Individual", viewModel);
}
}
So, how do I link the Project() or Article() methods to the CultureRoute as it requires to set the method explicitly in the RouteConfig ?

Related

webapi MVC - Return HomePage when create WebApi Empty

I've created an empty webapi project and I would like to add a homepage View. For some reason, it does not work - it always returns authorization access deny, but I've set the attribute [AllowAnonymous] on HomeController.
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 }
);
}
}
[AllowAnonymous]
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
return View();
}
}
Can anyone help with this issue please? Thanks

Dealing with multiple custom routes in MVC

I have my Home controller set up like this, going into different functions depending on the parameters it recieves.
Problem is in my home controller, it treats "gametwo" as a query for my route on my home controller.
Example
mysite.com/serchsomething <-- This will search the given string
mysite.com/gametwo <-- This also searches instead of going to gametwo controller
I have normal routeconfig.cs file, with just added attributeroutes.
What is the best way of dealing with routes with multiple parameters? So that they wont be ambigious or crash with any other routes? thanks
home controller
public ActionResult Index()
{
...
}
[HttpGet]
[Route("{Query}")]
public ActionResult Index(string Query)
{
...
}
[HttpGet]
[Route("{Query}/{Version}")]
public ActionResult Index(string Query, int Version)
{
...
}
GameTwo controller
[Route("GameTwo")]
public ActionResult Index()
{
return View();
}
routeconfig
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new {
controller = "Home",
action = "Index",
id = UrlParameter.Optional }
);
}
Try this above
Home Controller
[HttpGet]
public ActionResult serchsomething(string Query)
{
//do something
}
Game Two Controller
public ActionResult Index()
{
return View();
}
Routing
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
/*serchsomething action*/
routes.MapRoute(
name: "Your route name 1",
url: "serchsomething/{Query}",
defaults: new
{
controller = "home",
action = "serchsomething"
}
);
/*GameTwo Controller*/
routes.MapRoute(
name: "Your route name 2",
url: "GameTwo",
defaults: new
{
controller = "GameTwo",
action = "Index"
}
);
/* default*/
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}}
Are you giving correct controller name?. I am just seeing your url as
mysite.com/gametwo
but controller name as GameTwo Pls change it as GameTwo and try again.

Accessing views between different areas

I have two different Areas (User & Report) and they have two views (Login & Index) respectively.
What I am trying to do is on successful login user should be redirected to Report/Index page but its not working.
Its always inside User area only. Can some one point out what needs to be corrected here. Thanks!!! Help will be appreciated...
public class UserController : Controller
{
[HttpGet]
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(Models.User user)
{
if (ModelState.IsValid)
{
if (user.IsValid(user.UserName, user.Password))
{
return RedirectToAction("Report/Report/Index");
}
else
{
ModelState.AddModelError("", "Login data is incorrect!");
}
}
return View(user);
}
}
public class ReportController : Controller
{
// GET: Report/Report
public ActionResult Index()
{
return View();
}
}
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 = "User", action = "Login", id = UrlParameter.Optional },
namespaces: new[] { "DWP_MVC.Areas.User.Controllers" }
).DataTokens.Add("area", "User");
routes.MapRoute(
name: "Report",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Report", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "DWP_MVC.Areas.Report.Controllers" }
).DataTokens.Add("area", "Report");
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"User_default",
"User/{controller}/{action}/{id}",
new { action = "Login", id = UrlParameter.Optional }
);
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Report_default",
"Report/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
Your RedirectToAction() call must include the area name if you are using areas in your MVC structure.
In your example the following code would work:
return RedirectToAction("Index", "Report", new { area = "Report" });
As an aside, if you wish to redirect from one area to a controller/view which is not within the Area folder, you can utilize area = ""

Right way to Redirect a URL segment to MVC Controller

I have an existing Controller
public class HomeController : Controller
{
public ActionResult Index()
{
return Redirect("/Scorecard");
}
[OutputCache(Duration = 18000)]
public ActionResult Scorecard()
{
return View();
}
}
This currently Maps to http://siteurl/Home/Scorecard . I wanted to the segment http://siteurl/scorecard to redirect to this Controller Action . What would the best wayt to do this . I tried checking the RequestUrl in Session_Start in Global.aspx but the redirects dont seem to be happening . The other alternative I thought of was using a Different Controller like "ScorecardController" and then having a RedirectToAction("Scorecard","Home") in the Index view there.
you could add a FilterAccess class on your App_Start folder to do something like this:
public class FilterAcess : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
//Redirect
if (HttpContext.Current.Request.Url=="http://siteurl/scorecard"){
context.HttpContext.Response.Redirect("~/Home/Scorecard");
}
}
}
RedirectToAction is better way to do it, because, in case you change routing table later, redirect URL will be in adapted.
public class HomeController: Controller
{
public ActionResult Index()
{
return RedirectToAction("Scorecard");
}
[OutputCache(Duration = 18000)]
public ActionResult Scorecard()
{
return View();
}
}
You should also update RouteTable with additional route, before "Default" route:
public static void RegisterRoutes(RouteCollection routes)
{
routes.LowercaseUrls = true;
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "NoHomeSegmentInUrl",
url: "{action}/{id}",
defaults: new { controller = "Home", id = UrlParameter.Optional });
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
And, for lower case routes you need line routes.LowercaseUrls = true;

Controller action not found

I am using web api in my application. Web api 2 routing is working fine but the controller action routing is not found.
this is my global cs
public class MvcApplication : 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);
FluentValidationModelValidatorProvider.Configure();
}
}
Route Config
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}",
defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional }
);
}
}
Web api config
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultDataApi",
routeTemplate: "Api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Controller
public class LoginController : Controller
{
public ActionResult Index()
{
return View("~/Views/Default/Login.cshtml");
}
public ActionResult LogOut()
{
var ctx = Request.GetOwinContext();
var authManager = ctx.Authentication;
authManager.SignOut("ApplicationCookie");
return RedirectToAction("index", "home");
}
}
Change your Route config as
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "Focus/{controller}/{action}",
defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional }
);
}
}
Since "Focus" is defined in iis, it might or might not work with it. Please try, i don't have envoirment to test it right now.
Your url http://localhost/Focus/Login/Logout doesn't match the pattern of routeTemplate "Api/{controller}/{id}" in WebApiConfig. Try to match your url to the pattern.
Thank you deusExCore I solve the problem
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}",
defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional }
);
}
}

Resources