Building an MVC3 route that has two different parameters - asp.net-mvc-3

Here's what I want the user to see when visiting the page:
www.mywebsite.com/verify/sergiotapia/ASD98H1D9H12D081HD
Where sergiotapia is a username from my database, and OUAHSDFUOHASDFOUAHSDF is a generated field within User table.
This is for email verification purposes.
How would the route for this type of URL be, and also how would the ActionMethod signature be?
Any suggestions?

routes.MapRoute(
"Verify",
"verify/{username}/{token}",
new { controller = "Verify", action = "Index" }
);
and the controller:
public class VerifyController: Controller
{
public ActionResult Index(string username, string token)
{
...
}
}

Related

In MVC 3 how we can redirect user to default URL, depending on its role?

public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}",
new { controller = "User", action = "Index", id = UrlParameter.Optional }
);
}
If current user is admin then he should be redirect to admin page on entering root url ???
There are many ways (most of them custom) but I'd use default MVC functionality and keep routes as they are but rather have two controller actions depending on security role:
// actions part of UserController
public ActionResult Index()
{
...
}
[Authorize(Roles = "admin")]
[ActionName("Index")]
[AdminsOnly]
public ActionResult IndexAdmin()
{
...
}
This would automatically run the second one when users would be members of a particular role. But if you only have a particular user (admin) then you could change that attribute to be:
[Authorize(Users = "admin")]
If you're using some custom mechanism to define user type/role membership, you can always write your own authorization action filter.
But AuthoriseAttribute is not an action selector filter so MVC wouldn't be able to distinguish between the two withou creating a custom action selector filter AdminsOnlyAttribute. This one would do the check for you and you wouldn't the error that there were several actions for a request. In case of writing this custom filter, you can then also simply remove the AuthorizeAttribute as your action selector will check that already.
Other contenders
Custom Route
If this is not what you'd like you can always write your own custom Route class that redirects users to particular area depending on their username/role membership... Although redirection could as well be part of your Login action
[HttpPost]
public ActionResult Login(LoginCredentials user)
{
// authenticate
...
if (User.IsInRole("admin"))
{
return this.RedirectToAction("Index", "User", new { area = "Admin" });
}
return this.RedirectToAction("Index", "User");
}
This action assumes there's Admin area in your application.
Custom route constraint
The other possibility is to have custom route constraints. So you would actually define two routes but one having a particular constraint:
routes.MapRoute(
"Admin", // Route name
"{controller}/{action}/{id}",
new { area = "Admin", controller = "User", action = "Index", id = UrlParameter.Optional },
new { isAdmin = new AdminRouteConstraint() }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}",
new { controller = "User", action = "Index", id = UrlParameter.Optional }
);
This way you'd be able to route admins to admin area of your application and provide them with particular functionality they have there. But it doesn't bean that they need an admin area. That's just my route definition. You can define route defaults the way that you want.
You could implement this redirect in your Index action:
public class HomeController: Controller
{
public ActionResult Index()
{
if (User.IsInRole("admin"))
{
// The user is an administrator => redirect him to his own page
return RedirectToAction("SomeActionName", "SomeControllerName", new { area = "admin" });
}
// the use is either not authenticated or not in the admin role => render some view
return View();
}
}

Recommended API design with ASP.NET MVC3

I'm working with ASP.NET MVC 3. I'm kind of new to it. I think I'm starting to get the hang of it. But there is something that I'm trying to do, that I think makes sense, but maybe I'm wrong.
I'm trying to create an API around Order objects in my database. In order to get all of the orders in the system, I was going to expose an API that looks like the following:
/orders/
In cases where I wanted to get a specific Order, I would simply append an ID. In other words, the URL would look like this:
/orders/12345
In an effort to accomplish this, I created the following controller:
public class OrdersController : Controller
{
// GET: /Orders/
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index()
{
string result = "list of orders";
return Json(result, JsonRequestBehavior.AllowGet);
}
//
// GET: /Orders/{orderID}
public ActionResult Index(int id)
{
string result = "order:" + id;
return Json(result, JsonRequestBehavior.AllowGet);
}
}
In my AreaRegistration class, I have the following:
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"OrderList",
"{controller}/{action}",
new { action = "Index", controller="Orders" }
);
context.MapRoute(
"Order",
"{controller}/{action}/{id}",
new { action = "Index", controller = "Orders" }
);
}
When I attempted to access "/orders/", via the browser address bar, I get the JSON like I would expect. However, if I attempt to access "/orders/12345", I receive a 404. What am I missing?
Thank you
You need to also define proper routes in global.asax or use the default route which looks like {controller}/{action}/{id} where controller is defaulted to "Home", action is defaulted to "Index" and id is optional.
So /orders works because you have defined controller (orders), default action (Index) and missing id (which doesn't matter as it is optional)
But when you try /orders/12345 then you have defined controller (orders), action (12345) and missing id
So to make this work with only the default route the request should be /orders/index/12345
edit: for registering area routes you should use AreaRegistration class

C# - How to Rewrite a URL in MVC3

I have an URL like this:
http://website.com/Profile/Member/34
I need this URL runs like this:
http://website.com/Profile/John
Given John as profile name for the user id=34.
Can anyone give me directions to do that?
In global.asx you need to add a new route.
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
"Member", // Route name
"Profile/{member}", // URL with member
new { controller = "YourController", action = "Profile"}
);
}
You will still need to implement the action that handles looking up the profile based on {member}.
You have to add a custom route in the global.ascx.cs that will be used to redirect to the good controller. But I guess that "John" is not a unique value so you will have to keep the id in the Url, or if John is the username and is unique you can go with this url:
routes.MapRoute("Member", "Profile/{member}", new { controller = "Member", action = "Profile"});
Then in your controller you will have :
public ActionResult Profile(string username){
//fetch from the db
}
If "John" is not a unique value I suggest you use :
routes.MapRoute("Member", "Profile/{id}/{member}", new { controller = "Member", action = "Profile"});
So your Url will look like http://website.com/Profile/John/34 and youre controller :
public ActionResult Profile(int id){
//fetch from the db
}
Let me know if you need more help!

Add route for asp.net mvc 3

I need to be able to hande routes like this:
appdomain/city/City-state, so in case somebody used
appdomain/Washington/Washington-DC he retrieves proper info from proper controller action. For now can`t get what controller and action it should be to get this url and handle it properly.
To clear it a bit, there`s like no controller and action, but 2 parameters instead of them.
Why not adding a little help from a fixed path, like Show-City
routes.MapRoute(
"CityAndState",
"Show-City/{city}/{state}",
new { controller = "Cities", action = "Index", id = UrlParameter.Optional }
);
this will never interfere with your existing routes, and then you can use:
http://domain.com/Show-City/New York/NY
at your Index Action inside the Cities Controller you would have something like:~
public class CitiesController : Controller
{
public ActionResult Index(string city, string state)
{
// use city and state variables here
return View();
}
}
Try this:
routes.MapRoute("Foo", "{state}/{city}",
new { controller = "ControllerName", action = "ActionName" });
and in your class you'd have:
public class ControllerNameController : Controller {
public ActionResult ActionName(string state, string city) {
...
}
}

ASP.NET MVC 3 basic routing question

I am using ASP.NET MVC 3 and following the tutorial here http://www.asp.net/mvc/tutorials/asp-net-mvc-routing-overview-cs.
I am working on the sign up functionality and trying to make use of routing. So the typical scenario is:
When the user wants to sign up, he would get taken to /Account/SignUp.
Upon succesful sign up, he then gets redirected to /Account/SignUp/Successful.
I thought it would be simple enough but the "Successful" parameter never gets passed in the SignUp method in the controller.
public ActionResult SignUp(string msg)
{
// Do some checks on whether msg is empty or not and then redirect to appropriate view
}
In global.aspx.cs I've got pretty much the vanilla routing:
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional });
What am I failing to grasp here?
Your route parameter is called id, so:
public ActionResult SignUp(string id)
{
...
}
or change it to msg if you want:
"{controller}/{action}/{msg}"
Change the parameter from your method to id and create an get method for the /Account/SignUp action
public ActionResult SignUp()
{
//this is the initial SignUp method
}
[HttpPost]
public ActionResult SignUp(string id)
{
//User will be redirected to this method
}

Resources