[英]Reading FromUri and FromBody at the same time
我在web api中有一個新方法
[HttpPost]
public ApiResponse PushMessage( [FromUri] string x, [FromUri] string y, [FromBody] Request Request)
請求類就像
public class Request
{
public string Message { get; set; }
public bool TestingMode { get; set; }
}
我正在使用PostBody對localhost / Pusher / PushMessage進行查詢?x = foo&y = bar:
{ Message: "foobar" , TestingMode:true }
我錯過了什么嗎?
帖子正文通常是這樣的URI字符串:
Message=foobar&TestingMode=true
您必須確保HTTP標頭包含
Content-Type: application/x-www-form-urlencoded
編輯 :因為它仍然無法正常工作,我自己創建了一個完整的例子。
它打印正確的數據。
我還使用了.NET 4.5 RC。
// server-side
public class ValuesController : ApiController {
[HttpPost]
public string PushMessage([FromUri] string x, [FromUri] string y, [FromBody] Person p) {
return p.ToString();
}
}
public class Person {
public string Name { get; set; }
public int Age { get; set; }
public override string ToString() {
return this.Name + ": " + this.Age;
}
}
// client-side
public class Program {
private static readonly string URL = "http://localhost:6299/api/values/PushMessage?x=asd&y=qwe";
public static void Main(string[] args) {
NameValueCollection data = new NameValueCollection();
data.Add("Name", "Johannes");
data.Add("Age", "24");
WebClient client = new WebClient();
client.UploadValuesCompleted += UploadValuesCompleted;
client.Headers["Content-Type"] = "application/x-www-form-urlencoded";
Task t = client.UploadValuesTaskAsync(new Uri(URL), "POST", data);
t.Wait();
}
private static void UploadValuesCompleted(object sender, UploadValuesCompletedEventArgs e) {
Console.WriteLine(Encoding.ASCII.GetString(e.Result));
}
}
Web API使用命名規則。 帖子的方法應該用Post開始。
您應該將PushMessage重命名為方法名稱PostMessage。
web api默認也會監聽(取決於你的路線)'api / values / Message'而不是Pusher / Pushmessage。
[HttpPost]屬性不是必需的
您可以使用以下代碼在請求正文中發布json:
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
Request request = new Request();
HttpResponseMessage response = httpClient.PostAsJsonAsync("http://localhost/Pusher/PushMessage?x=foo&y=bar", request).Result;
//check if (response.IsSuccessStatusCode)
var createResult = response.Content.ReadAsAsync<YourResultObject>().Result;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.