Search code examples
routesasp.net-web-api2asp.net-web-api-routing

Web Api Routing with 404 response IHttpActionResult


I am trying to get the below routes to work but having an issue. The Route api/user/name works fine; I get the result "Whats up".

However, the Route api/user/Register results in 404.

private void ConfigureWebApi(HttpConfiguration config)
{
    config.MapHttpAttributeRoutes();

    var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
    jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
} 

The controller:

using System.Web.Http;
using Angular.Data.IServices;
using Angular.Data.Modals;

namespace Angular.Api.Controllers
{
    [RoutePrefix("api/user")]
    public class UserController : ApiController
    {
        private IUserService _userService;

        [Route("Name")]
        [HttpGet]
        public string Name()
        {
            return "Whats up";
        }


        [Route("Register")]
        public IHttpActionResult Register(User usr, string password)
        {
            _userService.RegisterUser(usr, password);

            //var response = Request.CreateResponse<User>(HttpStatusCode.Created, usr);

            //string uri = Url.Link("Register", new { id = usr.Id });
            //response.Headers.Location = new Uri(uri);
            return Ok("response");
        }
    }
}

Solution

  • Are you passing values for usr and password in your request? If not, that's probably the problem. You also will probably want to make a single model that contains all of the data that you need for registration, rather than splitting usr and password into two parameters.

    For example, try changing your method signature to this:

    [Route("Register")]
    [HttpGet]
    public IHttpActionResult Register(string username, string password)
    

    Then visit api/user/Register/?username=test&password=pwd in your browser and see if it works.