繁体   English   中英

Web API 参数始终为空

[英]Web API parameter is always null

我的 Web API 中有以下方法:

[AcceptVerbs("POST")]
public bool MoveFile([FromBody] FileUserModel model)
{
    if (model.domain == "abc")
    {
        return true;
    }
    return false;
}

FileUserModel定义为:

public class FileUserModel
{
    public string domain { get; set; }
    public string username { get; set; }
    public string password { get; set; }
    public string fileName { get; set; }
}

我试图通过 Fiddler 调用它,但是每当我这样做时,模型总是设置为 null。 在 Fiddler 中,我已发送 Composer 使用POST ,该 url 在那里并且正确,因为 Visual Studio 中的调试器在调用时中断。 我设置为的请求:

User-Agent: Fiddler 
Host: localhost:46992 
Content-Length: 127 
Content-Type: application/json

请求正文为:

"{
  "domain": "dcas"
  "username": "sample string 2",
  "password": "sample string 3",
  "fileName": "sample string 4"
}"

但是每当我在调试器遇到断点时运行 Composer 时,它总是显示模型为空。

您在发送的请求中缺少, 此外,由于包含双引号,您实际上发送的是 JSON 字符串,而不是 JSON 对象。 删除引号并添加逗号应该可以解决您的问题。

{
    "domain": "dcas", // << here
    "username": "sample string 2",
    "password": "sample string 3",
    "fileName": "sample string 4"
}

此外,由于您要发布模型,因此不需要[FromBody]属性。

[AcceptVerbs("POST")]
public bool MoveFile(FileUserModel model)
{
    if (model.domain == "abc")
    {
        return true;
    }
    return false;
}

那应该没问题。 有关这方面的更多信息,请参阅此博客

你需要像下面这样进行ajax调用

$(function () {
    var FileUserModel =    { domain: "dcas", username: "sample string 2", 
            password: "sample string 3", fileName: "sample string 4"};
    $.ajax({
        type: "POST",
        data :JSON.stringify(FileUserModel ),
        url: "api/MoveFile",
        contentType: "application/json"
    });
});

不要忘记将内容类型标记为 json 和服务器端 api 代码

[HttpPost]
public bool MoveFile([FromBody] FileUserModel model)
{
    if (model.domain == "abc")
    {
        return true;
    }
    return false;
}

在 ASP.NET Web API 中发送 HTML 表单数据

您遇到的问题是您正在发布带有双引号的 JSON 数据。 删除它们,它应该可以工作。

还要修复丢失的逗号:

{
  "domain": "dcas",
  "username": "sample string 2",
  "password": "sample string 3",
  "fileName": "sample string 4"
}

暂无
暂无

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

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