Asp.Net routing to action with parameters - asp.net

I have a routing config file with a following routing settings
routes.MapRoute(
name: "Login",
url: "Account/login/{username}/{password}",
defaults: new { controller = "Account", action = "Login"}
);
and I have a Login action in an Account Controller
[HttpPost]
public ActionResult Login(string username, string password)
{
// do some
}
[HttpGet]
public ActionResult Login()
{
//do some
}
I just want to call first action, with parameters not the second
Can you help me to fix this problem?

The first one is POST and second one is GET. So the HTTP verb which you use for calling will decide what gets called.

Related

Calling Controller HttpGet method by actionLink

I think I read almost all threads about actionLink and HttpGet but I don’t get the routing done.
In my startup class I have the default routing:
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}"
);
I call a website by the controller:
public class CollectionController : Controller
{
public async Task<IActionResult> Collection()
{
var viewModel = new CollectionViewModel();
…
return await Task.Run(() => View("~/Views/Sccm/Collection.cshtml", viewModel));
}
And in the View I will call another method in the controller to query more information:
#Html.ActionLink(linkText: item.DistinguishedName ?? "Not Found", actionName: "GetCollection", controllerName: "Collection",
routeValues: new { hostname = item.DistinguishedName }, htmlAttributes: null)
The method in the same controller looks like that but is never called (breaking point):
[HttpGet]
[ValidateAntiForgeryToken]
public async Task<IActionResult> GetCollection(string hostname)
{
Console.WriteLine("Hostname is: " + hostname);
return View();
}
I noticed that when I change routing in HttpGet I also get linked to another URL, but I never access the function. I assume I am missing some small detail. Any hint would be welcomed.
Thanks
Stephan
Maybe my problem is that the View is in another subfolder then die Controller name
Edit:
Damn it :(, I used the ValidateAntiForgeryToken in a getMethod
try this:
HttpGet("{hostname}")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> GetCollection(string hostname)
{
Console.WriteLine("Hostname is: " + hostname);
return View();
}

ASP.NET MVC 5 not seeing "{id}" route in controller

I've created a new ASP.NET MVC 5 project in Visual Studio 2015 Update 3, and everything is pretty standard. I have this controller:
public class UsersController : BaseController
{
[HttpGet]
public async Task<ActionResult> Newest()
{
var newestUsers = await Database.Users.OrderByDescending(u => u.ID).Take(100).ToListAsync();
return View(newestUsers);
}
[HttpGet]
[Route("{id}")]
public async Task<ActionResult> GetUser(long id)
{
var user = await Database.Users.FindAsync(id);
return View(user);
}
}
My BaseController derives from regular MVC Controller and it contains some common properties for my app. Nothing special.
When I go to /users/newest the appropriate page loads, but when I go to /users/1 I immediately get a 404 not found error. I've tried changing the route to ~/{id} but no avail. My route configuration is the standard, auto-generated one, I haven't touched it:
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 }
);
}
}
Why am not hitting the GetUser action?
UPDATE: For some reason, it started not working again. I didn't do anything. It was working after I've added routes.MapMvcAttributeRoutes();, it's still there but I started getting 404 again.
Okay I have no idea how it went away (or why it wasn't there) but I was missing the routes.MapMvcAttributeRoutes(); method in route configuration. Adding that method fixed the issue.
UPDATE: I've also needed to add RoutePrefix to get the routes working, and I have to explicitly add the correct route for any actions that have arguments. It's a pity that MVC can't map them by themselves.
Get ride of your additional Id routing above getuser - this isn't needed.
Your route is incorrect - it should be users/getuser/1

Create a link to redirect to the Web site Controller ActionResult from Web API

I need to send an email to the user for resetting password. Which contains a link to open the Password Reset page in Web site.
Both website & web api are in same domain.But different solutions.
I have created a link in web api.
var callbackUrl = Url.Link("ResetPassword", new { Controller = "Account", code = token });
But when it tested on postman it shows 'ResetPassword' could not be found in the route collection.
There is ResetPassword ActionResult in Account controller of Website.
[AllowAnonymous]
[Route(Name="ResetPassword")]
public ActionResult ResetPassword(string code)
{
return code == null ? View("Error") : View();
}
The RegisterRoutes method is,
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 }
);
}
I have not yet deployed the solution.
Will it work on deployment?
You've basically misplaced Route name with Action name. Please try to use this:
var callbackUrl = Url.Link("Default", new { Controller = "Account", Action ="ResetPassword", code = token });

Redirect using routing in MVC

I have ASP.NET MVC application.
I want my application to redirect from
example.com/Register
to
example.com/Account/Register
How can I do it with routes? It makes little sense to me to make controller only for this one task
public class RegisterController : Controller
{
public ActionResult Index()
{
return RedirectToAction("Register", "Account");
}
}
You don't need a redirect. You need a custom route
Add this route first (above "Default")
routes.MapRoute(
"Register",
"Register",
new { controller = "Account", action = "Register" }
);
This solution will leave the user on URL example.com/Register, but instantiate Controller Account, execute ActionResult Register, and return View Account/Register.

ASP.NET MVC - Routes

I'm working on an MVC application and I have and admin area... So what I need is:
When user makes request to admin (for example "/Admin/Post/Add") I need to map this to controller AdminPost and action Add... is it possible?
If your controller is named AdminPostController and you want it to map to '/Admin/Post/Add' then you can use:
routes.MapRoute("Admin", // Route name
"Admin/Post/{action}/{id}", // URL with parameters
new { controller = "AdminPost", action = "Add", id = "" } // Parameter defaults
);
Note the use of the parameter defaults.
If your controller is named AdminController and you just wanted to separate the request method then use the default:
routes.MapRoute("Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
Which will map '/Admin/Add/' to the controller:
public class AdminController : Controller {
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Add(int id) {
//...
}
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Add(int id) {
//...
}
}
Note the use of [AcceptVerbs] to identify which method to invoke for POST requests and GET requests.
See Scott Gu's blog for more details

Resources