MVC Web API通过x-www-form-encoded发布整数数组 [英] MVC Web API post an array of integers via x-www-form-encoded

查看:78
本文介绍了MVC Web API通过x-www-form-encoded发布整数数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做一些我认为非常简单的事情.我有一个HTML表单,该表单发布了一组整数输入,都称为级别":

I am trying to do something which I thought would be fairly simple. I have an HTML form that posts a set of integer inputs, all called "Level":

<form action="/api/levels" method="post">
<input name="Level" value="10" />
<input name="Level" value="20" />
<input name="Level" value="30" />
<button type="submit">submit</button>
</form>

我正试图将其接收到MVC Web API控制器方法中,如下所示:

I am trying to receive this into an MVC Web API controller method like this:

public void Post(int[] Level)
{

}

使用Chrome的网络工具进行诊断后,确认请求包含了我所期望的表单数据:

Diagnosing with Chrome's network tools confirms the request contains form data as I would expect:

Level=10&Level=20&Level=30

问题在于,Level参数始终为null.我显然希望它是一个包含3个值分别为10、20和30的数组.

The problem is that the Level parameter is always null. I would obviously want it to be an array with 3 elements of values 10, 20 and 30.

关于相似事物的帖子太多了,但是我找不到任何谈论Web API模型绑定而不是MVC的帖子,或者那些似乎抱怨抱怨旧版本发布的候选版本的帖子.

There are so many posts about similar things, but I can't find anything that talks about Web API model binding rather than MVC, or those that do seem to be complaining about changes made in older versions release candidates.

有人可以指出我正确的方向吗?

Can somebody point me in the right direction please?

推荐答案

如果要绑定主体 Level = 10& Level = 20& Level = 30 ,则需要使用操作方法参数就是这样.

If you want the body Level=10&Level=20&Level=30 to be bound, you will need your action method parameter to be like so.

public HttpResponseMessage Post(MyClass c)
{
    // Use c.Level array here
}

public class MyClass
{
    public int[] Level { get; set; }
}

相反,如果您希望操作方法参数为 int []级,则您的HTTP消息必须是这样.

Instead, if you want the action method parameter to be int[] Level, your HTTP message must be like so.

POST http://server/api/levels HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Content-Length: 11

=10&=20&=30

为此,请使用以下格式.

For this, have the form like so.

<form action="/api/levels" method="post">
    <input name="" value="10" />
    <input name="" value="20" />
    <input name="" value="30" />
    <button type="submit">submit</button>
</form>

这种怪异的原因是ASP.NET Web API将整个主体绑定到一个参数中.

The reason for this weirdness is that ASP.NET Web API binds the entire body into one parameter.

这篇关于MVC Web API通过x-www-form-encoded发布整数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆