Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have 2 methods (GET and POST) with the same route?

I would like to have 2 methods in my controller that have the same route but differ only in the HTTP method. Specifically, if my route looks like

routes.MapRoute(
    name: "DataRoute",
    url: "Sample/{user}/{id}/",
    defaults: new { controller = "Sample", action = "--not sure--", user = "", id = "" }
);

and I have 2 methods in my controller as such:

[HttpGet]
public void ViewData(string user, string id)

[HttpPost]
public void SetData(string user, string id)

The desired behavior is to call ViewData() if I GET Sample/a/b and call SetData() if I POST to Sample/a/b, the same URL.

I know I can just create 2 separate routes, but for design reasons I want to have one route differentiated only by GET and POST. Is there a way to configure either the route or controller to do this without having to create a new route?

like image 881
Booley Avatar asked Mar 11 '23 09:03

Booley


1 Answers

With attribute routing you should be able to set the same route with different methods.

[RoutePrefix("Sample")]
public class SampleController : Controller {
    //eg GET Sample/a/b
    [HttpGet]
    [Route("{user}/{id}")]
    public void ViewData(string user, string id) { ... }

    //eg POST Sample/a/b
    [HttpPost]
    [Route("{user}/{id}")]
    public void SetData(string user, string id) { ... }
}

Don't forget to enable attribute routing before convention-based routes

routes.MapMvcAttributeRoutes();

You should edit the SetData method to take some payload from the body of the POST.

public void SetData(string user, string id, MyCustomObject data) { ... }
like image 103
Nkosi Avatar answered Apr 07 '23 01:04

Nkosi