It seems ASP.NET implicitly interprets method named GetX
and PostX
as GET and POST methods respectively, because of their names are prefixed with HTTP method names. This is also the case for PUT and DELETE.
I have a method unfortunately named Delete
but I want it to be interpreted as a POST, so I explicitly specify it's a POST using the [HttpPost]
attribute. This works, as long as it's not declared inside an 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 work around this, without having to specify the HttpPostAttribute for each implementation?
Attributes on interface properties doesn't get inherited to the class, you may make your interface to an Abstract Class.
Found an answer from Microsoft:
The product team does not want to implement this feature, for two main reasons:
- Consistency with DataAnnotations.Validator
- Consistency with validation behavior in ASP.Net MVC
- tricky scenario: a class implements two interfaces that have the same property, but with conflicting attributes on them. Which attribute would take precedence?
SOURCES: Attribute on Interface members does not work
Like others have said, attributes are not inherited. DoSomething is not called using POST because of the attribute in your interface but because that is the default. Change it to GET in your interface and you will still notice POST calling it.
You can read more on how action selection is performed here in the section "Action Selection". (Item 3 answers your question regarding why DoSomething is called using POST)
Attributes aren't inherited from implemented interfaces, you'll have to declare the attribute on the concrete implementation (FooBarController). This overrides the convention-based binding.
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