其他分享
首页 > 其他分享> > CAPI-WebAPI路由不起作用

CAPI-WebAPI路由不起作用

作者:互联网

我有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控制器:

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

并从jquery调用:

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

它尝试调用,但失败:

enter image description here

App Insights说:

enter image description here

什么是无效的?

解决方法:

创建一个模型来保存发布的数据

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

更新控制器操作以从请求主体中获取该模型

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

最后,在客户端上更新请求

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

标签:asp-net-web-api2,c,routing
来源: https://codeday.me/bug/20191108/2009614.html