C# 将数据发布到 asp.net Web API

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15341744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 16:29:01  来源:igfitidea点击:

Posting data to asp.net Web API

c#asp.nethttpasp.net-mvc-4asp.net-web-api

提问by jdavis

I'm trying to figure out the new ASP.NET Web API.

我正在尝试找出新的 ASP.NET Web API。

So far I've been able to create this method signature and connect to it just fine and get a valid response...

到目前为止,我已经能够创建这个方法签名并很好地连接到它并获得有效的响应......

[HttpPost]
public HttpResponseMessage CreateAccount()

I am able to send a request to this method with fiddler and have verified that it is receiving the request.

我可以使用 fiddler 向此方法发送请求,并已验证它正在接收请求。

However, when I try to pass data is when I am running into a problem.

但是,当我尝试传递数据时,我遇到了问题。

The first thing I tried was...

我尝试的第一件事是......

[HttpPost]
public HttpResponseMessage CreateAccount([FromBody]string email, [FromBody]string password)

And I type

我输入

email:xyz,password:abc

电子邮件:xyz,密码:abc

into the body of the request in fiddler. When I do this I get a 500 error stating

进入 fiddler 中的请求正文。当我这样做时,我收到一个 500 错误说明

'Can't bind multiple parameters ('email' and 'password') to the request's content.'

'不能将多个参数('email' 和 'password')绑定到请求的内容。

I have also tried this as a method signature...

我也试过这个作为方法签名......

[HttpPost]
public HttpResponseMessage CreateAccount([FromBody]UserAccountRequestData data)

with the UserAccountRequestData being a simple POCO

UserAccountRequestData 是一个简单的 POCO

public class UserAccountRequestData
{
    public string Email { get; set; }
    public string Password { get; set; }
}

And I put

我把

{Email:xyz,Password:abc}

{电子邮件:xyz,密码:abc}

or

或者

data:{Email:xyz,Password:abc}

数据:{电子邮件:xyz,密码:abc}

into the body of the request. In both cases trying to populate the POCO I am able to reach the method while debugging, but the data object is always null.

进入请求正文。在尝试填充 POCO 的两种情况下,我都可以在调试时访问该方法,但数据对象始终为空。

I need to understand how to create API methods that accept both strongly typed POCOs and others that accept multiple primitive types like strings and ints.

我需要了解如何创建同时接受强类型 POCO 和其他接受多种原始类型(如字符串和整数)的 API 方法。

Thanks

谢谢

采纳答案by Darrel Miller

You need to set the Content-Typeheader to application/jsonand then provide valid JSON.

您需要将Content-Type标头设置为application/json然后提供有效的 JSON。

{"Email":"xyz","Password":"abc"}