Ajax到.NET无法绑定多个参数错误

时间:2017-05-17 13:22:07

标签: jquery asp.net .net ajax

当我尝试使用像这样的ajax传递值时:

 $.ajax({
     type: "PUT",
     dataType: 'json',
     url: "http://localhost:52930/api/person/",
     contentType: "application/json; charset=utf-8",
     data: {persoon1, persoon2, file}
 })
     .done(function( msg ) {
         alert("Test")
     });

其中person1和2是对象,文件是字节数组(JSON)。

在.NET中使用此功能

    public IHttpActionResult Put(Person personFrom , Person personTo , byte[] file)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest();
        }
        _personRepository.EncrypFileAndSendToPerson(file, personFrom  , personTo);
        return CreatedAtRoute("DefaultApi", new { controller = "Person", id = personTo.Id }, personTo);
    }

这是一个人类:

public class Person
{
    private RSAWithRSAParameterKey _rsaParameters;
    public Person()
    {
        _rsaParameters = new RSAWithRSAParameterKey();
        _rsaParameters.AssignNewKey();
        PrivateKey = _rsaParameters._privateKey;
        PublicKey = _rsaParameters._publicKey;
    }
    public int Id { get; set; }
    public string Name { get; set; }
    public string Password { get; set; }
    public string Salt { get; set; }
    public byte[] File { get; set; }
    public string PrivateKey { get; set; }
    public string PublicKey { get; set; }
    public EncryptedPacket Packet { get; set; }       
}

为什么我一直收到此错误以及如何解决?

完整错误

{Message: "An error has occurred.",…}
ExceptionMessage
:
"Can't bind multiple parameters ('personFrom' and 'file') to the request's content."
ExceptionType
:
"System.InvalidOperationException"
Message
:
"An error has occurred."
StackTrace
:
"   at System.Web.Http.Controllers.HttpActionBinding.ExecuteBindingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
↵   at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()
↵--- End of stack trace from previous location where exception was thrown ---
↵   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
↵   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
↵   at System.Web.Http.Controllers.AuthenticationFilterResult.<ExecuteAsync>d__0.MoveNext()
↵--- End of stack trace from previous location where exception was thrown ---
↵   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
↵   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
↵   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"

编辑:

这是我在console.log()data

中的值时得到的数据
{"personFrom":{"Id":2,"Name":"Sinan","Password":"wachtwoord2","Salt":"22ad8a4c-3175-4049-a9e0-f4f383c1cd09","File":null,"PrivateKey":"<RSAKeyValue><Modulus>3A86Zo99HaROAME/yU7POcogo4Zru62F+7PAXONv3Jm8l2RMfb4QlcCF483kXV85paVpbgI7en3O5eiFoTEUVUXP9InjpNg7X9jah8tJFLRvzIU74vHP7ccLXgOV5ztGUEGW2ESbpT6gkvNS6XvMyMS+r8rQt1mvNp3lhAErK81a6Pr1npVmew9cghikY5NOk5WcaAeh8pB4hPeGbTg33BRzEN+w8IeJh73EwKDz8fKklqbFv90qRUPciKKUStyCxTCU4yg43de4qcuzNXMXqjFF8NY0JXu+6L6yuRvrdFoBN4OWe2GLEGxVoemDWvO7rwP9qkSq51Bk9CnW4bd98w==</Modulus><Exponent>AQAB</Exponent><P>9dfUtHHiLbySstMMquL0QTazj8AI/S2IBpJX9kXgRQ9SaJ3l6VlbMmSTvjY3MgRK6OF3MISMlBRqAa0ptxttXyh1fEvS7B44XVrOOREEQQkRBo5Ly02vXFYudBApgd68EijBDcI0l3v7CzQu6Ng/ROLAYnrd4K9AzZ+cppRZ6tE=</P><Q>5SayKSK/R6I944RMeA/DYfep/KXiePSyE/MyI2A72q2bG8MaLG8w1JN1p5T5tfB2Tgyn/ePHjVoP7CYoRQz6PIcyxDDqRzyw5tDpQ0Rc3lTcJkM1WmWyB+9NDIV1mmhDgyUWAssS0IhKg/6HOat2dBbEPE+d9qgi9tjfQetKRYM=</Q><DP>9FLnxd1Yl3PNp4MwF7UuYpFmqvqC9HsHsOBIIy0W0guELwydredsRwzF+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eJh73EwKDz8fKklqbFv90qRUPciKKUStyCxTCU4yg43de4qcuzNXMXqjFF8NY0JXu+6L6yuRvrdFoBN4OWe2GLEGxVoemDWvO7rwP9qkSq51Bk9CnW4bd98w==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>","Packet":null},"personTo":{"Id":3,"Name":"Lennert","Password":"wachtwoord3","Salt":"daa4ccff-5764-41eb-b151-8b3cbc0f870b","File":null,"PrivateKey":"<RSAKeyValue><Modulus>44KWMkW7KFrnaK4qD90VSfiwLdttfpOYK+pApqXSAg2NnFLGxvI7AHoOWwQEQiYtQwyDjkNuxWsWxhYeMV9XwNaoba6hH/4iFx4ZR68FCJD5KsSfPuk+X4cf/R5auMKvLboKOFz9yRFYnBN17uQyI8NPhjTaAIRPJ5eTr/H+D6ug9hnwtz7tc/vpBPyjyomTcnUa9GVOrYAQ0RtsAvTJ2of9mT3G67WUhzIMqKsAFP6mObyAcyFgQx0uFdVFSFCOw26a0ASZM3juEVDT4OSWIZz3tWLD2acSPJTNxJFyvUMeEyc4dLPnPgZF/VypIjnuu4CZ/pplqS6N5Z3QhWgS2Q==</Modulus><Exponent>AQAB</Exponent><P>+Kk3iG6f03CG8yPWvN0CfkpHpVq2yvSguujscE6ZGW57cPYP3J02quqGvnCT5UUNxiyZt1tu/xh4HcapT2HVN1H4kCZdsKdbovGvjdAHzgZdNXunpLzIwvCbp9wskOqGClyZXKO1kEFhQ+u+69PuH9ifE8yxvzanfLc5irNY908=</P><Q>6jmP4ikBIawVTk5DVKKbvw9tkN0GdbTzMU7wTYHYoh61/k438AoOcnngr96orbqSQNtFucQ5IRonkHDqjjZrPlCYh+VpGCKR4Vl3+TWBc/ad1xiBRcmgfGyd72CRqYU3sjsfNe1zYkgvJqpUf0frafUz2tqBR+Bk/jC/RAhRyVc=</Q><DP>Ch6AxwmRcX5Tz5M2yurHjjIhpkYByFKaM+EEtjFMo69OULOCw7yWG/B9WUSlkB/2RolMHB0ZcEIjqTqLa1KU5bJtRhh5m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VFSFCOw26a0ASZM3juEVDT4OSWIZz3tWLD2acSPJTNxJFyvUMeEyc4dLPnPgZF/VypIjnuu4CZ/pplqS6N5Z3QhWgS2Q==</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>","Packet":null},"file":"{\"1\":115,\"2\":100,\"3\":100,\"4\":115,\"5\":100,\"6\":97}"}

3 个答案:

答案 0 :(得分:1)

最有可能发生这种情况,因为参数不是可选的,并且您不会将FromBody属性应用于参数。试试这个:

public IHttpActionResult Put(
    [FromBody] Person personFrom,
    [FromBody] Person personTo,
    [FromBody] byte[] file)
{
    ...
}

如果没有帮助尝试创建新模型以将请求映射到包含所有属性的请求:

public class PutModel
{
    public Person PersonFrom {get; set;}
    public Person PersonTo {get; set;}
    public byte[] File {get; set;}
}

在您的操作中定义单个参数:

public IHttpActionResult Put([FromBody] PutModel model)
{
    ...
}

并确保属性名称正确为@Jay建议。

data: {
    "personFrom": persoon1,
    "personTo": persoon2,
    "file": file
}

此外,根据控制台中的消息,文件是一个对象,而不是JS中的数组。尝试明确地将其设为像Converting a JS object to an array中的数组:

var array = $.map(file, function(value, index) {
    return value;
});

答案 1 :(得分:0)

你需要像这样传递价值

    $.ajax({
    type: "PUT",
    dataType: 'json',
    url: "http://localhost:52930/api/person/",
    contentType: "application/json; charset=utf-8",
    data: {
        "personFrom": persoon1,
        "personTo": persoon2,
        "file": file
    }
})
        .done(function (msg) {
            alert("Test")
        });

答案 2 :(得分:0)

尝试以下代码

 $.ajax({
                    type: 'PUT',
                    url: 'http://localhost:52930/api/person/',
                    dataType: 'application/json',
                    data: {
                         personFrom : persoon1, 
                         personTo : persoon2,
                         file: file                       
                    },
                    success: function (data) {
                        alert("Application Updated Successfully");
                    },
                    error: function (err) { 
                    }
                });

你想在javascript中填充对象,如:

var persoon1 = {
Id: $("#id").val(),
Name: $("#Name").val(),
}

你的方法就像:

[ResponseType(typeof(void))] //whatever the response
public IHttpActionResult Put(Person personFrom , Person personTo , byte[] file)
    {
    }