Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Attribute Routing - Default Controller Index with GET and POST

We have an MVC 5.1 project and are using attribute routing. Everything is working fine except the default page which has a login form on it.

[RoutePrefix("Home")] 
public class HomeController : BaseController
{
    [Route("~/")]
    [Route]
    [Route("Index")]
    [HttpGet]
    public ActionResult Index()
    {
        var model = new LoginViewModel();

        return View(model);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Index(String Username, String Password)

The form is displayed via the GET fine but upon the POST we get...

HTTP Error 405.0 - Method Not Allowed

The page you are looking for cannot be displayed because an invalid method (HTTP verb) is being used.

Normally the default route would handle both the POST and GET fine.

   routes.MapRoute(
        name: "Default",
       url: "{controller}/{action}/{id}/{dealerId}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
     );

Obviously I am missing something here on the routing for the post on the default route as subsequent posts on other pages work fine.

Has anyone done this?

Thanks,

like image 636
Foxster Avatar asked Feb 07 '14 15:02

Foxster


People also ask

What is the difference between routing and attribute routing in MVC?

ASP.NET MVC offers two approaches to routing: The route table, which is a collection of routes that can be used to match incoming requests to controller actions. Attribute routing, which performs the same function but is achieved by decorating the actions themselves, rather than editing a global route table.

What is the default route pattern in MVC?

The default route table contains a single route (named Default). The Default route maps the first segment of a URL to a controller name, the second segment of a URL to a controller action, and the third segment to a parameter named id. The Default route maps this URL to the following parameters: controller = Home.


Video Answer


1 Answers

Ok seems all I have to do is add

 [Route("~/")]
 [Route]
 [Route("Index")]
 [HttpPost]
 [ValidateAntiForgeryToken]

 public ActionResult Index(String Username, String Password)

Obvious really! Long Day!

like image 74
Foxster Avatar answered Sep 28 '22 08:09

Foxster