Error while calling Webapi in my asp.net project

2019-08-23 05:40发布

This is my api code that return successfull json data while using get method

public Question[] Get() {
    getQuestion obj = new AllDataAccess.getQuestion();
    return obj.questionList().ToArray();
}

This is my post method data that accept the value and save in database

public void Post([FromBody] string question) {
    SaveQuestion obj = new AllDataAccess.controller.SaveQuestion();
    obj.savaData(question);
}   

This is the method that call my api

$.ajax({
    type: 'POST',
    contentType: "application/json; charset=utf-8",
    url: 'http://localhost:53893/api/values',
    data: "{'question':'" + $("#submit").value + "'}",
    dataType: 'json',
    async: false,
    success: function(data, status) {    
        console.log(status);
    },
    error: function(err) {
        console.log(err);
    }
});

Now the problem is when i post the data with one textbox value its give me a message in console that "nocontent" and record save in data base with null value

2条回答
兄弟一词,经得起流年.
2楼-- · 2019-08-23 06:00

If you want to use FromBody, you can do so. JavaScript

$.ajax({
    type: "POST",
    //default content-type, could be omitted
    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
    url: 'http://localhost:53893/api/values/post',
    data: {'': $("#submit").val()}
});

API action

[HttpPost]
public void Post([FromBody]string question)
{
     SaveQuestion obj = new AllDataAccess.controller.SaveQuestion();
     obj.savaData(question);
}

You had these issues.

  1. Wrong content-type for your ajax call.
  2. Data was not posted correctly.
  3. val() should be used instead of .value.
  4. API action should be decorated with [HttpPost].
查看更多
爷、活的狠高调
3楼-- · 2019-08-23 06:14

It seems that your ajax url is wrong. You should specify the action name (post). Also, use JSON.stringify to retrieve proper json from javascript object.

    var postData = { question:$("#submit").val() };
    $.ajax({
       type: 'POST',
       contentType: "application/json; charset=utf-8",
       url: 'http://localhost:53893/api/values/post',
       data: JSON.stringify(postData),
       dataType: 'json',
       success: function (data,status) {
           console.log(status);
       },
       error: function (err) {
           console.log(err);
       }
    });

In the server side, you should create a model class for Post method;

public class PostInput
{
    public string Question { get; set; }
}

And then Post method looks like;

[HttpPost]
public void Post([FromBody]PostInput input)
{
     SaveQuestion obj = new AllDataAccess.controller.SaveQuestion();
     obj.savaData(question);
}
查看更多
登录 后发表回答