简体   繁体   English

如何正确发送PUT请求到webAPI应用程序?

[英]How to send PUT request properly to webAPI application?

My javascript code: 我的JavaScript代码:

$.ajax({
        type: "PUT",
        url: "/api/WordsAPI/"+wordData.ID,
        data: { word: wordData}
    });

Part of my C# code: 我的C#代码的一部分:

// PUT: api/WordsAPI/5
    [ResponseType(typeof(void))]
    public IHttpActionResult PutWord(int id, Word word)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        if (id != word.ID)
        {
            return BadRequest();
        }

        [...]
    }

In VisualStudio debugger I can see that app executes second BadRequest. 在VisualStudio调试器中,我可以看到该应用程序执行了第二个BadRequest。 All data in variable "word" on server side is null. 服务器端变量“ word”中的所有数据均为空。 I have no idea why. 我不知道为什么。 "id" variable is OK, it stores proper ID. “ id”变量可以,它存储正确的ID。

In javascript debugger in Firefox everything seems to be ok. 在Firefox中的javascript调试器中,一切似乎正常。 wordData isn't null (wordData.id is sent properly to server) and I can see that all data was succesfully sent to server. wordData不为空(wordData.id已正确发送到服务器),我可以看到所有数据都已成功发送到服务器。

What could be wrong? 有什么事吗 What should I do? 我该怎么办?

EDIT: 编辑:

Request in firefox (this is what is sent by browser): firefox中的请求(这是浏览器发送的): 在此处输入图片说明

The server-side code works fine for me. 服务器端代码对我来说很好用。 However, the JavaScript should be as follows. 但是,JavaScript应该如下。

$.ajax({
        type: "PUT",
        url: "/api/WordsAPI/"+wordData.ID,
        data: wordData
});

I'm assuming wordData is an Object with a sample definition 我假设wordData是一个带有示例定义的Object

var wordData = {
    ID: 5,
    UsersLanguage: "string data"
    // etc
}

I agree with Vsevolod You need to add the [FromBody] tag in front of the Word class of the API method for sure. 我同意Vsevolod。您需要确保在[FromBody]方法的Word类的前面添加[FromBody]标签。 Secondly as Simoco says you need to make sure that the wordData you are sending has the same structure as your Word model. 其次,正如Simoco所说,您需要确保要发送的wordData具有与Word模型相同的结构。

meaning if you class looked like this 意思是如果你上课看起来像这样

public class Word{
int id {get; set;}
string someText {get; set;}
}

Then your Word you are sending from the javascript needs to have the same structure 然后,您从javascript发送的Word必须具有相同的结构

var word = {id : 1, someText: "text string"};

I would also suggest that you debug in VS on the method to make sure its being called. 我还建议您在VS上对该方法进行调试以确保其被调用。 You can see what is being picked up if you hover over the Word parameter 如果将鼠标悬停在Word参数上,则可以看到正在拾取的内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM