2016-08-02 13 views
12

Aşağıdaki kodu gereksinimi göstermek için basitleştirilmiştir. Neyin yanlış olduğunu öğrenebilir miyim? [FromBody] özniteliğini kullanarak iki Parametre (A ve B bu durumda) almak için görünmüyor olabilir.WebAPI Selfhost: İsteğin içeriğine birden fazla parametre bağlayamıyorum

hata mesajı

"isteğin içeriğine birden çok parametre ('A' ve 'B') bağlamak Can not" dir Ben A veya B yalnızca birini varsa bu bir sorun oluşturmaz.

Web API:

[Route("API/Test"), HttpPost] 
public IHttpActionResult Test([FromBody] int A, [FromBody] int B) 

Müşteri:

HttpClient client = new HttpClient(); 
var content = new FormUrlEncodedContent(
    new Dictionary<string, string> { 
     { "A", "123" }, 
     { "B", "456" } 
    }); 
client.PostAsync("http://localhost/API/Test", content).Result; 

cevap

3

Web API kodunu deneyin:

[DataContract] 
public class Model 
{ 
    [DataMember] 
    public int A { get; set; } 

    [DataMember] 
    public int B { get; set; } 
} 

[Route("API/Test"), HttpPost] 
public IHttpActionResult Test([FromUri] Model model) 
17

Web Api Bence birden [FromBody] params desteklemez. Ama sen api eylemine fazla parametre geçirmeden, Api modelini kullanabiliriz .:

public class YourApiModel 
{ 
    public int A{ get; set; } 

    public int B { get; set; } 

    //...other properties  
} 

Bundan sonra, sadece API kontrolör Testinde bu kullanabilirsiniz:

// POST: api/test 
    public IHttpActionResult Post([FromBody] YourApiModel model) 
    { 
     //do something 
    } 

faydası Umut.