weixin_33697898 2017-11-17 11:44 采纳率: 0%
浏览 34

将int传递给webapi

I know this has been asked a thousand times. But I can't find my error. I narrowed it down by testing it without a parameter, which worked and then tried various things. Like, get or post, [FromBody] or not. etc. Perhaps I should just show my code or I should stop for today and just celebrate that it is almost weekend.

[HttpGet] // also tried post instead of get
public HttpResponseMessage Get(int id)
{
    return Request.CreateResponse(HttpStatusCode.OK); // breakpoint set, not hit
}

My Js code:

var myObj = {};
myObj["id"] = parseInt(id);

var json = JSON.stringify(myObj);
alert(json);  // display: { id = 2134 }, seems fine to me

$.ajax({
    type: "GET", // also tried post
    dataType: "json",
    url: '/api/CheckPossible/Get',
    data: json,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function () {
        alert('success');
    },
    error: function () {
        alert('failure');
    }
});

I have received a lot of bad requests (400) and I did got it to work without a parameter. So it is not a routing issue.

edit

$.ajax({
    type: "GET",
    dataType: "json",
    url: '/api/CheckPossible/Get/?id=1234', // also tried Get?id=1234
    contentType: "application/json; charset=utf-8",
    success: function () {
        alert('success');
    },
    error: function () {
        alert('failure');
    }
});

Did not work. Perhaps I am missing something else too

  • 写回答

1条回答 默认 最新

  • weixin_33713503 2017-11-17 11:48
    关注

    You can't pass a http message body to a GET method, you have to pass parameters either in the URL or in the header. For a web api you should pass them in the URL and you can do this as a query string or as part of the URL.

    To get it to work with the query string change the url to

    url: '/api/CheckPossible/?id=' + myObj["id"],
    

    leave out the data as this won't do anything with get.

    If you want to make the parameter a part of the URL then change your route to include it. I prefer the Route attribute for flexible routing, you can also change the global routing scheme.

    [HttpGet] // also tried post instead of get
    [Route("api/CheckPossible/{id:int}"]
    public HttpResponseMessage Get(int id)
    {
    }
    

    and change your url to

    url: '/api/CheckPossible/' + myObj["id"]
    
    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测