How to stop the ASP.NET web API from implicitly interpreting the HTTP method?

ASP.NET seems to implicitly interpret the method named GetX and PostX as the GET and POST methods, respectively, since their names have the HTTP method name prefix. This also applies to PUT and DELETE.

I have a method, unfortunately, with the name Delete , but I want it to be interpreted as POST, so I explicitly specify its POST using the [HttpPost] attribute. This works if it is not declared inside the interface ...

 public interface IFooBarController { [HttpPost] void DoSomething(); [HttpPost] void Delete(int id); } public class FooBarController : IFooBarController { public void DoSomething() { // This API method can only be called using POST, // as you would expect from the interface. } public void Delete(int id) { // This API method can only be called using DELETE, // even though the interface specifies [HttpPost]. } } 

How can I get around this without specifying an HttpPostAttribute for each implementation?

+7
c # asp.net-mvc asp.net-web-api
source share
4 answers

Like others, attributes are not inherited. DoSomething is not called using POST because of the attribute in your interface, but because it is the default value. Change it to GET in your interface and you will still notice that POST calls it.

You can learn more about choosing an action here in the "Selecting an Action" section. (Point 3 answers your question regarding why DoSomething is called using POST)

+2
source

Attributes of interface properties are not inherited to the class; you can make your interface an abstract class.

Found an answer from Microsoft :

The development team does not want to implement this feature for two main reasons:

  • Consistency with DataAnnotations.Validator
  • Consistency with validation in ASP.Net MVC
  • complex scenario: a class implements two interfaces that have the same property, but with conflicting attributes on them. Which attribute takes precedence?

SOURCES: Attribute for interface members not working

+4
source

Attributes are not inherited from implemented interfaces; you need to declare an attribute of a specific implementation (FooBarController). This overrides the binding based on convention.

+1
source

use [username] and specify it as you want

-2
source

All Articles