I want to route REST service url in the following way:
/User/Rest/ -> UserRestController.Index()
/User/Rest/Get -> UserRestController.Get()
/User/ -> UserController.Index()
/User/Get -> UserController.Get()
So basically I'm making a hardcoded exception for Rest in the url.
I'm not very familiar with MVC routing. So what would be a good way to achieve this?
Routing Tables. In ASP.NET Web API, a controller is a class that handles HTTP requests. The public methods of the controller are called action methods or simply actions. When the Web API framework receives a request, it routes the request to an action.
If you are familiar with ASP.NET MVC, Web API routing is very similar to MVC routing. The main difference is that Web API uses the HTTP verb, not the URI path, to select the action. You can also use MVC-style routing in Web API.
Routing is how Web API matches a URI to an action. Web API 2 supports a new type of routing, called attribute routing. As the name implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web API.
Summary. Attribute routing in ASP.NET Core 3.0 allows us to define specific, customized routes for actions in our systems. Said routes are applied directly at the controller action level, allowing for high cohesion between route and action.
Wherever you register your routes, commonly in global.ascx
routes.MapRoute(
"post-object",
"{controller}",
new {controller = "Home", action = "post"},
new {httpMethod = new HttpMethodConstraint("POST")}
);
routes.MapRoute(
"get-object",
"{controller}/{id}",
new { controller = "Home", action = "get"},
new { httpMethod = new HttpMethodConstraint("GET")}
);
routes.MapRoute(
"put-object",
"{controller}/{id}",
new { controller = "Home", action = "put" },
new { httpMethod = new HttpMethodConstraint("PUT")}
);
routes.MapRoute(
"delete-object",
"{controller}/{id}",
new { controller = "Home", action = "delete" },
new { httpMethod = new HttpMethodConstraint("DELETE") }
);
routes.MapRoute(
"Default", // Route name
"{controller}", // URL with parameters
new { controller = "Home", action = "Index" } // Parameter defaults
,new[] {"ToolWatch.Presentation.API.Controllers"}
);
In your controller
public ActionResult Get() { }
public ActionResult Post() { }
public ActionResult Put() { }
public ActionResult Delete() { }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With