Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 671
Rudey Avatar asked Mar 10 '16 12:03

Rudey


3 Answers

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 image 170
raoon Avatar answered Nov 08 '22 01:11

raoon


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)

like image 37
CodingYoshi Avatar answered Nov 08 '22 02:11

CodingYoshi


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.

like image 37
Leon Cullens Avatar answered Nov 08 '22 02:11

Leon Cullens