24 NİSAN 2012, Salı
Nasıl Sistemi kullanmak için.Net.Karmaşık bir tür yazı için HttpClient?
Web API kullanarak çalışmak istiyorum özel bir karmaşık türü var.
public class Widget
{
public int ID { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
Ve burada web API denetleyicisi yöntemi. Öyle gibi: bu nesne göndermenizi istiyorum
public class TestController : ApiController
{
// POST /api/test
public HttpResponseMessage<Widget> Post(Widget widget)
{
widget.ID = 1; // hardcoded for now. TODO: Save to db and return newly created ID
var response = new HttpResponseMessage<Widget>(widget, HttpStatusCode.Created);
response.Headers.Location = new Uri(Request.RequestUri, "/api/test/" widget.ID.ToString());
return response;
}
}
Ve şimdi Sistemi kullanmak istiyorum.Net.HttpClient yöntemi çağrısı yapmak. Ancak, PostAsync yöntemi haline geçer, ve inşa etmek için nasıl emin değilim. İşte bazı örnek client kodu.
var client = new HttpClient();
HttpContent content = new StringContent("???"); // how do I construct the Widget to post?
client.PostAsync("http://localhost:44268/api/test", content).ContinueWith(
(postTask) =>
{
postTask.Result.EnsureSuccessStatusCode();
});
Nasıl web API anlayabileceği bir şekilde HttpContent nesne oluşturabilirim?
CEVAP
5 ŞUBAT 2013, Salı
HttpRequestMessage<T>
genel olmuşturkaldırıldı. Bu :
new HttpRequestMessage<Widget>(widget)
artık çalışmaz.
Bunun yerine, from this post, ASP.NET takımın bazı new calls Bu işlevi desteklemek için yer verdi:
HttpClient.PostAsJsonAsync<T>(T value) sends “application/json”
HttpClient.PostAsXmlAsync<T>(T value) sends “application/xml”
Yani, yeni bir kod (**15) olur
Widget widget = new Widget()
widget.Name = "test"
widget.Price = 1;
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:44268");
client.PostAsJsonAsync("api/test", widget)
.ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode() );
Bunu Paylaş:
Nasıl web görünümü ile özel yazı tipi ...
Nasıl Win otomatik terazi sistemi yazı...
Nasıl HTML Çeviklik paketi kullanmak i...
bir öğe veri-öznitelik değeri için bir...
Nasıl bir bağımlılık en son sürümünü k...