404未找到 - 使用angularjs使用Web API

时间:2015-06-20 19:19:28

标签: asp.net-mvc angularjs rest asp.net-web-api asp.net-web-api-routing

我有我的控制器代码:

 [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);
    }

和我的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 }
            );
    }
}

最后是我的js代码

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

问题是我收到了搜索到的电子邮件的响应(找不到404),尽管它存在于Users表的电子邮件字段中。

2 个答案:

答案 0 :(得分:1)

我已经解决了它:

https://

无需溃败

答案 1 :(得分:0)

路由请求一个id,但你发送一个字符串 将routeTemplate更改为

 routeTemplate: "api/{controller}/{action}/",