404 Not found - consume the Web API by angularjs

1.4k views Asked by At

I have my controller code:

 [HttpGet]
    [ActionName("Email")]
    public HttpResponseMessage GetByEmail(string email)
    {
        Users user = db.Users.Find(email);
        if (user == null)
        {
            throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
        }
        return Request.CreateResponse(HttpStatusCode.OK, user);
    }

and my WebApiConfig:

    public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        // Configure Web API to use only bearer token authentication.
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        config.Routes.MapHttpRoute(
            name: "EmailApi",
            routeTemplate: "api/{controller}/{action}/{email}",
            defaults: new { email = RouteParameter.Optional }
            );
    }
}

and finally my js code

$http.get('/api/users/Email/' + NewUser.Email)      
         .success(function (response) {
             console.log(response);                  // prints 404 not found 
         });

The problem is that I get response (404 not found ) for the searched email although it exists in the email field in the Users table.

2

There are 2 answers

8
Sajal On

the route request an id but you send a string change the routeTemplate to

 routeTemplate: "api/{controller}/{action}/",
0
Abdulrhman Alsri On

I have solved it:

    public Users Get(string Email)
    {
        Users user = db.Users.Find(Email);
        if (user == null)
        {
            throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
        }
        return user;
    }

No need for rout