Oleg Sh
Oleg Sh

Reputation: 9013

WebAPI routing does not work

I have WebApiConfig

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();
   config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Web API controller:

[RoutePrefix("api/Trip")]
public class TripApiController : ApiController
{
    [Route("SaveRouting")]
    [HttpPost]
    public async Task<HttpResponseMessage> SaveRouting(string points, int tripId, decimal totalMileage)
    {
        // ......
        return Request.CreateResponse(HttpStatusCode.OK);
    }

and call from jquery:

            $.post("/api/trip/SaveRouting",
                { points: JSON.stringify(arrayStops), tripId: $("#hdTripId").val(), totalMileage: tMiles },
                function(resp) {
                    App.unblockUI(blockElRouting);
                });

it tries to call, but failure:

enter image description here

App Insights says:

enter image description here

what is invalid?

Upvotes: 3

Views: 47

Answers (1)

Nkosi
Nkosi

Reputation: 247511

Create a model to hold the posted data

public class RouteModel {
    public string points { get; set; } 
    public int tripId { get; set; }
    public decimal totalMileage { get; set; }
}

Update the controller action to expect that model from the body of the request

[RoutePrefix("api/Trip")]
public class TripApiController : ApiController {
    [Route("SaveRouting")]
    [HttpPost]
    public async Task<IHttpActionResult> SaveRouting([FromBody] RouteModel route) {
        if(ModelState.IsValid) {
            string points = route.points; 
            int tripId = route.tripId;
            decimal totalMileage = route.totalMileage;

            // ......

            return Ok();
        }
        return BadRequest(ModelState);
    }
}

Finally, on the client side update the request

var model = { points: arrayStops, tripId: $("#hdTripId").val(), totalMileage: tMiles };

$.ajax({
    type: "POST",
    url: "/api/trip/SaveRouting",
    data: JSON.stringify(model),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data){
        App.unblockUI(blockElRouting);
    }
});

Upvotes: 3

Related Questions