2017-06-16 13 views
5

tôi nhận được báo lỗi khi đi qua các thông số,MVC Web API, Lỗi: có thể không ràng buộc nhiều tham số

"Can't bind multiple parameters"

đây là mã của tôi

[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

có thể trùng lặp của [WebAPI Nhiều Đặt/Post thông số] (https://stackoverflow.com/questions/14407458/webapi-multiple-put-post-parameters) –

+0

Kính gửi Paul. Tôi vừa kiểm tra câu hỏi đề cập đến, điều này không trùng lặp vì câu hỏi đó khác với câu hỏi hiện tại của tôi. Cảm ơn bạn – Tom

+0

Bạn có đang sử dụng API Web 1 hoặc 2 không? –

Trả lời

11

Tham khảo: 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.

tôi nhấn mạnh

Điều đó đang được nói. Bạn cần tạo một mô hình để lưu trữ dữ liệu tổng hợp dự kiến.

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

và sau đó cập nhật hành động để hy vọng mô hình mà trong cơ thể

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

đảm bảo để gửi payload đúng

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) { 

    }, 
}) 
Các vấn đề liên quan