Search code examples
c#asp.netasp.net-mvchttpasp.net-mvc-routing

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?


Solution

  • 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) { ... }