I am working on a new project and i have decided to use attribute routing alone. This is my RouteConfig file:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
//routes.MapRoute(
// name: "Default",
// url: "{controller}/{action}",
// defaults: new { controller = "HomeController", action = "Index", id = UrlParameter.Optional }
//);
}
This is my controller:
[RoutePrefix("home")]
public class HomeController : Controller
{
[Route]
[Route("~/")]
public ActionResult Index()
{
var status = HttpContext.User.Identity.IsAuthenticated;
ViewBag.Title = "Home Page";
return View();
}
[Route("test")]
public ActionResult Test()
{
return View();
}
}
I've realised that typically all my attributes are working but i want the Index method to run on application start. Say https://example.com and then the Index method is fired as if i entered the url https://example.com/home/index. I get a blank space when i do say https://example.com.
Can anyone please help me understand why i get a blank space and also how to set the default application start route using attribute routing? I've been surfing the internet for hours but i can't lay my hands on anything.
In your case you should still set a default route. That way the site knows where to start. From there everything else should work as you intended.
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{action}",
defaults: new { controller = "Home", action = "Index" }
);
}
Here is my Home Controller.
public class HomeController : FrontOfficeControllerBase {
public HomeController() {
}
public ActionResult Index() {
...
return View();
}
}
Other than that this keeps my route config clean as I use attribute routing everywhere else.
Try this:
[RoutePrefix("home")]
public class HomeController : Controller
{
[Route("index")]
[Route("~/", Name = "default")]
public ActionResult Index()
{
...
}
...
}
Related
My controller:
public class AjaxController : Controller
{
private readonly IGenerationUnitMobileService _generationUnitMobileService;
public AjaxController(IGenerationUnitMobileService generationUnitMobileService)
{
_generationUnitMobileService = generationUnitMobileService;
}
public IActionResult MobileExistToAnotherGenerationUnit(String mobile, long generation_unit_id)
{
//ViewBag.Result = _generationUnitMobileService.MobileExistToAnotherGenerationUnit(mobile,generationUnitId);
return View();
}
}
And My view file is very simple:
#model PgcgSms.WebSite.Models.GenerationUnitMobileViewModel
#{
Layout = "~/Views/Shared/_Ajax.cshtml";
}
#ViewBag.Result
This is so much straight forward. But when I browse at: http://localhost:57216/Ajax/MobileExistToAnotherGenerationUnit/01719393045/1
I am getting the following error message:
This localhost page can’t be found
No webpage was found for the web address: http://localhost:57216/Ajax/MobileExistToAnotherGenerationUnit/01719393045/1
Search Google for localhost 57216 Ajax Mobile Exist To Another Generation Unit 01719393045
HTTP ERROR 404
I checked the view file and spellings several times. Whats wrong with my code?
In the RouteConfig.cs file you will have to specify the default route.
For Example:
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 = "AjaxController", action = "MobileExistToAnotherGenerationUnit", id = UrlParameter.Optional }
);
}
}
I just want to customize routes in asp.net mvc ,
This is a blog website and I want to access controller methods using
wwww.sitename.com/blog/{blogtitle}
www.sitename.com/blog/{action}
Blog Controller
public class BlogController : Controller
{
public ActionResult Index(string title)
{
return View();
}
[Route("post-blog")]
[HttpPost]
public ActionResult Post(Blog blog,HttpPostedFileBase blogimage)
{
//some coe
}
[Route("post-blog")]
public ActionResult Post()
{
if (Request.Cookies["userInfo"]==null)
{
return Redirect("/login");
}
return View();
}
}
Here is route Config
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//routes.Canonicalize().Www();
routes.Canonicalize().Lowercase();
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "freelogomaker", id = UrlParameter.Optional }
);
}
But I am unable to hit action name "Index" using www.site.com/blog/titlename
But I can access "post-blog" using www.site.com/blog/post-blog
Please help me I am beginner in asp.net mvc routing.
Add your parameter to the route attribute within {} brackets to indicate that it should be read from the URL, and not from something else (such as POST body, dependency injections, etc)
[Route("{title}")]
public ActionResult Index(string title)
{
return View();
}
I also like to add the RoutePrefix attribute to the controller to make it a bit clearer.
[RoutePrefix("blog")]
public class BlogController : Controller
My RouteConfig file is
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Employee", action = "Index", id = UrlParameter.Optional }
);
My controller is
[Route("EMS/{Employee}")]
public ActionResult Index()
{
return View();
}
my working url is
http://localhost:6628/EMS/Employee
but i want to use simple http://localhost:6628 as my default url as without MapMvcAttributeRoutes() it was working fine
How can i use both of them in same project like default controller action must be employee and index and on click route url EMS/Employee working like this
<td>
<input type="button" id="ROUTE" value="ROUTE" onclick="location.href='#Url.Action("Employee", "EMS")'" class="btn-info" />
</td>
If the controller for example is EmployeeController
public class EmployeeController {
[HttpGet]
[Route("")] //Matches GET /
[Route("EMS/Employee")] //Matches GET EMS/EMployee
public ActionResult Index() {
return View();
}
}
You can use multiple routes on the actions.
I have a TextObject controller, which is meant to be accessed by "~/umt/text/{action}/{id?}", as defined in the controller using attribute routing, but the action link:
#Html.ActionLink("Index", "Index", "TextObject")
ignores Attribute Routing and uses the Conventional routing definitions, producing ~/TextObject/ instead of the desired ~/umt/text/
the TextObjectController:
[Authorize]
[RouteArea("umt")]
[RoutePrefix("text")]
[Route("{action=index}/{id?}")]
public class TextObjectController : Controller
{
.....
public async Task<ActionResult> Index()
{
return View(await db.TextObjects.ToListAsync());
}
.....
}
My route config:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//Enable Attribute Routing
routes.MapMvcAttributeRoutes();
AreaRegistration.RegisterAllAreas();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
Is there any additional configuration required on the controller to make the action link work or does it not work with attribute routing?
I'd like to keep it simple, and it routes correctly going directly through the url, but the ActionLink helper seems to not like something about it.
I can't see that you specify your defauld area it RouteConfig so your action link should look like:
#Html.ActionLink("TextObject", "Index", "Index", new { area = "umt" }, null)
I'm having an issue that is driving me nuts.
I have an MVC 4 WebAPI application that has several Areas defined.
My Jobs Area Send controller (SendController.cs) is defined like so:
namespace TargetAPI.Areas.Jobs.Controllers
{
public class SendController : ApiController
{
[HttpPost]
public HttpResponseMessage Index(SendRequest req)
{
try
{
//blah blah
}
catch (Exception ex)
{
//blah blah
}
}
}
}
My Jobs Area Registration (JobsAreaRegistration.cs) is defined like so:
namespace TargetAPI.Areas.Jobs
{
public class JobsAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Jobs";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Jobs_long",
"Jobs/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional },
new[] { "TargetAPI.Areas.Jobs.Controllers" }
);
}
}
}
My RouteConfig.cs says:
namespace TargetAPI
{
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 },
namespaces: new string[] { "TargetAPI.Controllers" }
);
}
}
}
When I run the route debugger on it I get:
(source: boomerang.com)
But when I try to post to the URL "Jobs/Send" I get:
The controller for path '/Jobs/Send' was not found or does not implement IController.
I've tried so many iterations and combinations my head is spinning. Any ideas?
Thanks!
Turns out the WebAPI does NOT handles Areas! Imagine my surprise. So I found a GREAT post http://blogs.infosupport.com/asp-net-mvc-4-rc-getting-webapi-and-areas-to-play-nicely/. Now I am moving forward.
In addition to not supporting Areas (because MapHTTPRoute doesn't have namespace support), The API controller must use MapHttpRoute, not MapRoute as in this example (after removing area):
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Note the absence of {action}, the Method's are not Actions, put are taken from the HTTP request: Get, Head, etc...
I had the same problem, the solution was simple: I forgot to add files _ViewStart.cshtml and _Layout.cshtml, and can help you