Error while calling Webapi in my asp.net project

☆樱花仙子☆ 提交于 2020-01-16 08:39:11

问题


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


回答1:


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



回答2:


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].


来源:https://stackoverflow.com/questions/48020084/error-while-calling-webapi-in-my-asp-net-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!