Mvc customize routes - asp.net

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

Related

set Default routing url and attribute route ? how to

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.

Default attributing routing not working

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()
{
...
}
...
}

ActionLink ignoring attribute routing settings

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)

MVC 4 Web API Areas 404 Error: "The controller for path '/Jobs/Send' was not found or does not implement IController."

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

Page does not exist in MVC

I am following this tutorial to create the first mvc application (Create a Movie Database Application).
I already added the create view, but when I click on the Create new link, the page does not exist. Typical 404 error.
I tried
/home/create
/create
/create.aspx
/home/create.aspx
I am very newbie at MVC, so please dont laugh. :)
EDIT: GLobal .asax
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
HomeController
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Movies.Models;
namespace Movies.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
private LearningEntities _db = new LearningEntities();
public ActionResult Index()
{
return View(_db.Movies1.ToList());
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude = "Id")] Movie movieToCreate)
{
if (!ModelState.IsValid)
return View();
_db.AddToMovies1(movieToCreate);
_db.SaveChanges();
return RedirectToAction("Index");
}
}
}
You need a Get as well as Post Create method in your controller. You need the following
public ActionResult Create()
{
return View();
}
public ActionResult Create([Bind(Exclude = "Id")] Movie movieToCreate)
{
....
}
Edit: The URL to your create view is /Home/Create
You dont have a create "get" action.
Basically the create action you have there is for when a form is submitted.
You need this code from the tutorial:
// GET: /Home/Create
public ActionResult Create()
{
return View();
}
The Create you have is for HttpPost which you'll use when you are trying to create an entity. Initially you'll need to have a controller method with HttpGet create method which will let you enter data for a new entity. Also, make sure your view is in Views->home folder.

Resources