2017-06-16 61 views
5

otrzymuję błąd podczas przechodzenia parametry,MVC Web API Błąd: Nie można powiązać wiele parametrów

"Can't bind multiple parameters"

tutaj jest mój kod

[HttpPost] 
public IHttpActionResult GenerateToken([FromBody]string userName, [FromBody]string password) 
{ 
    //... 
} 

Ajax:

$.ajax({ 
    cache: false, 
    url: 'http://localhost:14980/api/token/GenerateToken', 
    type: 'POST', 
    contentType: "application/json; charset=utf-8", 
    data: { userName: "userName",password:"password" }, 

    success: function (response) { 
    }, 

    error: function (jqXhr, textStatus, errorThrown) { 

     console.log(jqXhr.responseText); 
     alert(textStatus + ": " + errorThrown + ": " + jqXhr.responseText + " " + jqXhr.status); 
    }, 
    complete: function (jqXhr) { 

    }, 
}) 
+0

Możliwy duplikat [WebAPI Multiple put/parametrów post] (https://stackoverflow.com/questions/14407458/webapi-multiple-put-post-parameters) –

+0

Drogi Pawle. Właśnie sprawdziłem, czy pytanie nie jest duplikatem, ponieważ to pytanie różni się od mojego bieżącego pytania. Dziękujemy – Tom

+0

Czy używasz Web API 1 lub 2? –

Odpowiedz

11

Dotyczy: Parameter Binding in ASP.NET Web API - Using [FromBody]

At most one parameter is allowed to read from the message body. So this will not work:

// Caution: Will not work!  
public HttpResponseMessage Post([FromBody] int id, [FromBody] string name) { ... } 

The reason for this rule is that the request body might be stored in a non-buffered stream that can only be read once.

podkr

takiej sytuacji. Potrzebujesz stworzyć model do przechowywania oczekiwanych zagregowanych danych.

public class AuthModel { 
    public string userName { get; set; } 
    public string password { get; set; } 
} 

a następnie zaktualizować działań oczekują tego modelu w organizmie

[HttpPost] 
public IHttpActionResult GenerateToken([FromBody] AuthModel model) { 
    string userName = model.userName; 
    string password = model.password; 
    //... 
} 

upewniając się, aby wysłać ładunek prawidłowo

var model = { userName: "userName", password: "password" }; 
$.ajax({ 
    cache: false, 
    url: 'http://localhost:14980/api/token/GenerateToken', 
    type: 'POST', 
    contentType: "application/json; charset=utf-8", 
    data: JSON.stringify(model), 
    success: function (response) { 
    }, 

    error: function (jqXhr, textStatus, errorThrown) { 

     console.log(jqXhr.responseText); 
     alert(textStatus + ": " + errorThrown + ": " + jqXhr.responseText + " " + jqXhr.status); 
    }, 
    complete: function (jqXhr) { 

    }, 
})