簡體   English   中英

WebAPI路由不起作用

[英]WebAPI routing does not work

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

它試圖打電話,但失敗了:

在此輸入圖像描述

App Insights說:

在此輸入圖像描述

什么是無效的?

創建一個模型來保存發布的數據

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM