JohnPete22
JohnPete22

Reputation: 523

ASP.NET Core MVC : MapControllerRoute with generic pattern not allowing POST

I have the following setup created:

app.MapControllerRoute(
    name: "Product",
    pattern: "product/{*url}",
    defaults: new { controller = "Product", action = "Index" });
public class ProductController : BaseStoreController
{
    [HttpGet]
    public IActionResult Index(string url)
    {
         ....
    }

    [ValidateAntiForgeryToken]
    [HttpPost]
    public IActionResult AddProduct(ProductViewModel model)
    {
        ....
    }
}
@using (Html.BeginForm("AddProduct", "Product", FormMethod.Post))
{
    ......

    <button type="submit" class="btn btn-danger ms-2">Add</button>
}

The generic routing is forcing all GET and POST requests to hit the Index GET action. I tried adding the following (in different variations) above the generic routing declaration, but still the Index GET action is triggered. I also tried creating an Index POST action and having the form POST to it instead of the AddProduct action, but still the Index GET action is always triggered on any GET or POST method.

Any help would be appreciated.

app.MapControllerRoute(
    name: "AddProduct",
    pattern: "product/addproduct",
    defaults: new { controller = "Product", action = "AddProduct" });

Upvotes: 0

Views: 38

Answers (2)

Ruikai Feng
Ruikai Feng

Reputation: 11896

all uri like "/product/a" ,"/product/b" would match the parttern: pattern: "product/{*url}", also, the both index action and addproduct action would match the parttern,but index action has higher priority than addproduct action,so index action would always been hit

see this part of document

I tried adding the following (in different variations) above the generic routing declaration, but still the Index GET action is triggered.

since the first parttern could match the url,the second parttern would be ignored,see this part of document

Upvotes: 0

Mark Rabjohn
Mark Rabjohn

Reputation: 1723

If you're "AddProduct" method were called "Index" I'd expect that your first route would work for you. Also, if you were willing to use the differing url "/product/addproduct", I'd expect for your AddProduct method to be called via your second route example.

Since you state you tried both methods, then I'm thinking that perhaps [ValidateAntiForgeryToken] is failing and actually causing a redirect to /Index which would then be a GET. I'd use Telerik Fiddler (or possibly Chrome or Edge's Network tab) to see whether there was actually a redirect. I'd also probably try the program with the ValidateAntiForgery commented out briefly.

If it turns out to be the case that the Anti Forgery is causing a problem, you'll have to read up on how to render your form properly in the View (I can't remember how it's done).

Mark

Upvotes: 0

Related Questions