web-api
  1. web-api-routing-for-custom-actions

Routing for Custom Actions - (Web API Custom Method Names)

Routing is an important feature of ASP.NET Web API that allows you to map incoming HTTP requests to controller actions. By default, Web API maps HTTP verbs to controller methods based on convention. In some cases, however, you may want to use custom method names for your controller actions. In this tutorial, we'll look at how to use custom method names in Web API routing.

Syntax

To use custom method names in Web API routing, you can use the [ActionName] attribute to map a custom method name to a controller action. The syntax is as follows:

[HttpPost]
[ActionName("CustomMethodName")]
public IHttpActionResult MyCustomAction() {
    // custom action logic here
}

Example

Suppose you have a Web API controller that performs a custom action to search for a product by name. You can use the [ActionName] attribute to map a custom method name to this action as follows:

[HttpPost]
[ActionName("SearchProductByName")]
public IHttpActionResult MyCustomAction(string name) {
    // custom action logic here
}

Now, when a request is made to POST /api/products/SearchProductByName, the MyCustomAction method will be invoked.

Explanation

By default, Web API maps HTTP verbs to controller methods based on convention. For example, a GET request maps to a method named Get, a POST request maps to a method named Post, and so on. However, in some cases, such as when you want to use custom method names, you can use the [ActionName] attribute to explicitly map a method name to a controller action.

Use

Using custom method names in Web API routing is useful when you want to use descriptive method names that are more meaningful than the generic HTTP verb names.

Important Points

Here are some important points to keep in mind when using custom method names in Web API routing:

  • Use the [ActionName] attribute to map a custom method name to a controller action.
  • Be sure to use unique method names to avoid conflicts with other actions.

Summary

In this tutorial, we discussed routing for custom actions in Web API. We covered syntax, example, explanation, use, and important points of using custom method names to map incoming HTTP requests to controller actions. By using custom method names, you can make your Web API more descriptive and meaningful, which can improve the overall experience for clients of your API.

Published on: