0
votes

I have a little problem with routing in my app Angular + wep api. I want to put user, and it doesn't work. Server returns 404 and error:

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

and

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'."

It's strange because the method exists.

The entirety of my code follows:

My route:

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

My put method:

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

My angular put method:

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;
}
1

1 Answers

0
votes

Specify the [FromUri] and [FromBody] to define parameter mapping

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

You have to make sure that the post request HTTP header contains

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