net项目中调用Webapi时出错

net项目中调用Webapi时出错

本文介绍了在我的asp.net项目中调用Webapi时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

这是我的api代码,在使用get方法时返回成功的json数据

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

这是调用我的api的方法

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

推荐答案

您的Ajax网址似乎不正确.您应该指定操作名称(post).另外,使用JSON.stringify从javascript对象中检索正确的json.

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

在服务器端,您应该为Post方法创建模型类;

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

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

然后Post方法看起来像;

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

这篇关于在我的asp.net项目中调用Webapi时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 15:56