Greg Gum
Greg Gum

Reputation: 37895

web api controller action methods

I am trying to get a web api call to work: I want to submit an email address and then on the server, the method will validate and return null or a message.

This is what I tried:

    [Post]
    public string validate(string email) {
        return this._contextProvider.ValidateEmail(email);
    }

However, I get this message returned to the client: No HTTP resource was found that matches the request URI 'https://localhost:44300/breeze/data/validate

The payload looks like this: {email: "[email protected]"}

Upvotes: 1

Views: 61

Answers (1)

Greg Gum
Greg Gum

Reputation: 37895

The problem, it turns out, was the parameter binding.

In the Web API, binding is handling differently than MVC. By default, simple types are extracted from the URI, not the body. Complex types are extracted from the body of the message.

I then added the [FromBody] Attribute to the Action Method, and it then found the action method. But alas, the email parameter was null.

public string validate([FromBody]string email) {
        return this._contextProvider.ValidateEmail(email);
    }

Turns out when using this trick, the body must NOT be json, but constructed like a querystring - [email protected]. I didn't want do do that, so ended up creating a class to accept the parameter, and that worked as expected.

public class ParameterizedAction {
    public string Parameter { get; set; }
}

 public string validate(ParameterizedAction arg) {
        return this._contextProvider.ValidateEmail(arg.Parameter);
 }

This article has more info: http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-and-action-selection

as well as this one: http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/

Upvotes: 2

Related Questions