2017-01-10 76 views
0

我在我的應用Angular + wep api中路由有點問題。我想把用戶,它不工作。服務器返回404和錯誤:Angular - Web api路由放置方法

Failed to load resource: the server responded with a status of 404 (Not Found)

Message":"No HTTP resource was found that matches the request URI ' http://localhost:53544/api/Users/PutUser/1 '.","MessageDetail":"No action was found on the controller 'Users' that matches the name 'PutUser'."

這很奇怪,因爲該方法存在。

我的代碼的全部如下:

我的路線:

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

我put方法:

[HttpPut] 
    [ActionName("PutUser/{userId}")] 
    [ResponseType(typeof(void))] 
    public IHttpActionResult PutUser(int userId, User user) 
    { 
     if (!ModelState.IsValid) 
     { 
      return BadRequest(ModelState); 
     } 

     if (userId != user.Id) 
     { 
      return BadRequest(); 
     } 

     db.Entry(user).State = EntityState.Modified; 

     try 
     { 
      db.SaveChanges(); 
     } 
     catch (DbUpdateConcurrencyException) 
     { 
      if (!UserExists(userId)) 
      { 
       return NotFound(); 
      } 
      else 
      { 
       throw; 
      } 
     } 

     return StatusCode(HttpStatusCode.NoContent); 
    } 

我的角度put方法:

this.PutUser = function (userId, user) { 
    var promise = $http({ 
     method: 'PUT', 
     url: 'api/Users/PutUser/' + userId, 
     data: user 
    }) 
    .then(function (response) { 
     return "update"; 
    }, 
    function (response) { 
     return response.statusText; 
    }); 
    return promise; 
} 

回答

0

指定[FromUri]和[FromBody]來確定INE參數映射

[HttpPut] 
    [ActionName("PutUser/{userId}")] 
    [ResponseType(typeof(void))] 
    public IHttpActionResult PutUser([FromUri]int userId, [FromBody]User user) 
    { 

你必須確保發佈請求的HTTP頭中包含

Content-Type: application/x-www-form-urlencoded 
+0

感謝您的幫助,但我發現錯誤,我刪除了動作名稱參數{用戶id},然後它的工作原理 – ryckoshet