Adam Terlson
Adam Terlson

Reputation: 12730

Remote Validator on Model in MVC4 to /api/ Route

How does one configure a Remote validator via data annotations to make its call at /api/{controller} instead of /{controller}/{action}?

My model:

public class MyModel
{
    [Required]
    public string Name { get; set; }
    [EmailAddress(ErrorMessage="We need a valid email."), Remote(....)]
    public string Email { get; set; }
}

No matter what I try, the URL called by that remote validator is /foo/bar instead of just doing a get to /api/foo.

Is there any support for WebAPI in remote validators?

I'd like my email uniqueness check to use the .NET validators if at all possible (rather than having to do it manually), my form is submitted via AJAX, I'd like to validate the email prior to form submission, and using a remote validator pointing at an API controller seems like a natural choice.

Upvotes: 1

Views: 1637

Answers (1)

Max Toro
Max Toro

Reputation: 28618

Cannot use a Web API controller. This is a limitation of the RemoteAttribute. To avoid conflicts with MVC controllers, to match a Web API route you must include an httproute key, which RemoteAttribute doesn't do.

You should be able to inherit RemoteAttribute and override GetUrl to make it work.

Upvotes: 3

Related Questions