本文整理汇总了C#中System.Net.Http.HttpClient.DeleteAsync方法的典型用法代码示例。如果您正苦于以下问题:C# HttpClient.DeleteAsync方法的具体用法?C# HttpClient.DeleteAsync怎么用?C# HttpClient.DeleteAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.Http.HttpClient
的用法示例。
在下文中一共展示了HttpClient.DeleteAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: DeleteData
public async Task<Result> DeleteData(Uri uri, StringContent json, UserAuthenticationEntity userAuthenticationEntity, string language = "ja")
{
using (var httpClient = new HttpClient())
{
try
{
var authenticationManager = new AuthenticationManager();
Result result = new Result(false, "");
if (RefreshTime(userAuthenticationEntity.ExpiresInDate))
{
var tokens = await authenticationManager.RefreshAccessToken(userAuthenticationEntity.RefreshToken);
result.Tokens = tokens.Tokens;
}
httpClient.DefaultRequestHeaders.Add("Accept-Language", language);
httpClient.DefaultRequestHeaders.Add("Origin", "http://psapp.dl.playstation.net");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", userAuthenticationEntity.AccessToken);
var response = await httpClient.DeleteAsync(uri);
var responseContent = await response.Content.ReadAsStringAsync();
result.IsSuccess = response.IsSuccessStatusCode;
result.ResultJson = responseContent;
return result;
}
catch (Exception)
{
return new Result(false, string.Empty);
}
}
}
示例2: RunClient
/// <summary>
/// Runs an HttpClient issuing a POST request against the controller.
/// </summary>
static async void RunClient()
{
var handler = new HttpClientHandler();
handler.Credentials = new NetworkCredential("Boris", "xyzxyz");
var client = new System.Net.Http.HttpClient(handler);
var bizMsgDTO = new BizMsgDTO
{
Name = "Boris",
Date = DateTime.Now,
User = "Boris.Momtchev",
};
// *** POST/CREATE BizMsg
Uri address = new Uri(_baseAddress, "/api/BizMsgService");
HttpResponseMessage response = await client.PostAsJsonAsync(address.ToString(), bizMsgDTO);
// Check that response was successful or throw exception
// response.EnsureSuccessStatusCode();
// BizMsg result = await response.Content.ReadAsAsync<BizMsg>();
// Console.WriteLine("Result: Name: {0}, Date: {1}, User: {2}, Id: {3}", result.Name, result.Date.ToString(), result.User, result.Id);
Console.WriteLine(response.StatusCode + " - " + response.Headers.Location);
// *** PUT/UPDATE BizMsg
var testID = response.Headers.Location.AbsolutePath.Split('/')[3];
bizMsgDTO.Name = "Boris Momtchev";
response = await client.PutAsJsonAsync(address.ToString() + "/" + testID, bizMsgDTO);
Console.WriteLine(response.StatusCode);
// *** DELETE BizMsg
response = await client.DeleteAsync(address.ToString() + "/" + testID);
Console.WriteLine(response.StatusCode);
}
示例3: AlbumsControllerTest
private static async Task AlbumsControllerTest(HttpClient client)
{
// create album
await client.PostAsync("Albums/Create",
new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("title", "album 009") }));
await client.PostAsync("Albums/Create",
new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("title", "album 010") }));
// get all albums
Console.WriteLine(await client.GetStringAsync("Albums/All"));
// update album
await client.PutAsync("Albums/Update",
new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("id", "2"),
new KeyValuePair<string, string>("year", "2014"),
new KeyValuePair<string, string>("producer", "gosho ot pochivka")
}));
// delete album
await client.DeleteAsync("Albums/Delete/1");
// add song to album
await client.PutAsync("Albums/AddSong?albumId=2&songId=2", null);
// add artist to album
await client.PutAsync("Albums/AddArtist?albumId=2&artistId=2", null);
}
示例4: GetResponseAsync
public async Task<HttpResponseMessage> GetResponseAsync(RestCommand command, string data = "")
{
try
{
using (var handler = new HttpClientHandler())
{
if (_credentials != null)
handler.Credentials = _credentials;
using (var httpClient = new HttpClient(handler))
{
ConfigureHttpClient(httpClient);
switch (command.HttpMethod)
{
case HttpMethod.Get:
return await httpClient.GetAsync(command.FullResourceUri);
case HttpMethod.Put:
return await httpClient.PutAsync(command.FullResourceUri, new StringContent(data));
case HttpMethod.Post:
return await httpClient.PostAsync(command.FullResourceUri, new StringContent(data));
case HttpMethod.Delete:
return await httpClient.DeleteAsync(command.FullResourceUri);
}
throw new Exception(string.Format("The command '{0}' does not have a valid HttpMethod. (Type: {1})", command, command.GetType().FullName));
}
}
}
catch (Exception e)
{
throw new Exception("An error occured while performing the request.", e);
}
}
示例5: Main
static void Main(string[] args)
{
System.Threading.Thread.Sleep(100);
Console.Clear();
Console.WriteLine("**************************开始执行获取API***********************************");
HttpClient client = new HttpClient();
//Get All Product 获取所有
HttpResponseMessage responseGetAll = client.GetAsync(url + "api/Products").Result;
string GetAllProducts = responseGetAll.Content.ReadAsStringAsync().Result;
Console.WriteLine("GetAllProducts方法:" + GetAllProducts);
//Get Product根据ID获取
HttpResponseMessage responseGetID = client.GetAsync(url + "api/Products/1").Result;
string GetProduct = responseGetID.Content.ReadAsStringAsync().Result;
Console.WriteLine("GetProduct方法:" + GetProduct);
//Delete Product 根据ID删除
HttpResponseMessage responseDeleteID = client.DeleteAsync(url + "api/Products/1").Result;
// string DeleteProduct = responseDeleteID.Content.ReadAsStringAsync().Result;
Console.WriteLine("DeleteProduct方法:" );
//HttpContent abstract 类
//Post Product 添加Product对象
var model = new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M };
HttpContent content = new ObjectContent(typeof(Product), model, new JsonMediaTypeFormatter());
client.PostAsync(url + "api/Products/", content);
//Put Product 修改Product
client.PutAsync(url + "api/Products/", content);
Console.ReadKey();
}
示例6: FakeServer_CapturesAllRequests
public void FakeServer_CapturesAllRequests()
{
using (var fakeServer = new FakeServer())
{
fakeServer.Start();
var baseAddress = fakeServer.BaseUri;
Action<Action, int> repeat = (a, times) =>
{
for (var i = 0; i < times; i++)
a();
};
var url1 = "/request1";
var url2 = "/request2";
var url3 = "/request3";
var url4 = "/request4";
var httpClient = new HttpClient();
httpClient.DeleteAsync(new Uri(baseAddress + url1)).Wait();
repeat(() => httpClient.GetAsync(new Uri(baseAddress + url2)).Wait(), 2);
repeat(() => httpClient.PostAsync(new Uri(baseAddress + url3), new StringContent(url3)).Wait(), 3);
repeat(() => httpClient.PutAsync(new Uri(baseAddress + url4), new StringContent(url4)).Wait(), 4);
fakeServer.CapturedRequests.Count(x => x.Method == Http.Delete && x.Url == url1).Should().Be(1);
fakeServer.CapturedRequests.Count(x => x.Method == Http.Get && x.Url == url2).Should().Be(2);
fakeServer.CapturedRequests.Count(x => x.Method == Http.Post && x.Url == url3 && x.Body == url3).Should().Be(3);
fakeServer.CapturedRequests.Count(x => x.Method == Http.Put && x.Url == url4 && x.Body == url4).Should().Be(4);
}
}
示例7: inline_call_to_invalidate_using_expression_tree_with_param_is_correct
public void inline_call_to_invalidate_using_expression_tree_with_param_is_correct()
{
var client = new HttpClient(_server);
var result = client.DeleteAsync(_url + "Delete_parameterized").Result;
_cache.Verify(s => s.RemoveStartsWith(It.Is<string>(x => x == "webapi.outputcache.v2.tests.testcontrollers.inlineinvalidatecontroller-get_c100_s100_with_param")), Times.Exactly(1));
}
示例8: CallWebService
private void CallWebService(string baseUrl, string authenticationUrl, string taskUrl, string application, string userName, string password)
{
var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
using (var httpClient = new HttpClient(handler))
{
httpClient.BaseAddress = new Uri(baseUrl);
httpClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var result = httpClient.PostAsJsonAsync(authenticationUrl, new
{
Application=application,
UserName = userName,
Password = password
}).Result;
result = httpClient.DeleteAsync(taskUrl).Result;
result.EnsureSuccessStatusCode();
//var userProfile = await result.Content.ReadAsAsync<UserProfile>();
//if (userProfile == null)
// throw new UnauthorizedAccessException();
//return userProfile;
}
}
示例9: DeleteHotel
private static void DeleteHotel(string serverUrl, int deleteHotelNo)
{
Console.WriteLine("Exercise6");
Console.WriteLine(" 6) Delete(HTTP Delete) the Hotel number 200");
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(serverUrl);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
string deleteUrl = "api/hotels/" + deleteHotelNo;
var response = client.DeleteAsync(deleteUrl).Result;
Console.WriteLine("Delete Async " + deleteUrl);
Console.WriteLine(response.StatusCode);
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Succcesfull delete");
}
else
{
Console.WriteLine("Someting went wrong, hotel not deleted");
}
}
catch (Exception)
{
throw;
}
}
}
示例10: Main
static void Main(string[] args)
{
Uri baseAddress = new Uri("http://ncs-sz-jinnan:3721");
HttpClient httpClient = new HttpClient { BaseAddress = baseAddress };
IEnumerable<Contact> contacts = httpClient.GetAsync("/api/contacts").Result.Content.ReadAsAsync<IEnumerable<Contact>>().Result;
Console.WriteLine("当前联系人列表");
ListContacts(contacts);
Contact contact = new Contact { Id = "003", Name = "王五", EmailAddress = "[email protected]", PhoneNo = "789" };
Console.WriteLine("\n添加联系人003");
httpClient.PutAsync<Contact>("/api/contacts", contact, new JsonMediaTypeFormatter()).Wait();
contacts = httpClient.GetAsync("/api/contacts").Result.Content.ReadAsAsync<IEnumerable<Contact>>().Result;
ListContacts(contacts);
contact = new Contact { Id = "003", Name = "王五", EmailAddress = "[email protected]", PhoneNo = "987" };
Console.WriteLine("\n修改联系人003");
httpClient.PostAsync<Contact>("/api/contacts", contact, new XmlMediaTypeFormatter()).Wait();
contacts = httpClient.GetAsync("/api/contacts").Result.Content.ReadAsAsync<IEnumerable<Contact>>().Result;
ListContacts(contacts);
Console.WriteLine("\n删除联系人003");
httpClient.DeleteAsync("/api/contacts/003").Wait();
contacts = httpClient.GetAsync("/api/contacts").Result.Content.ReadAsAsync<IEnumerable<Contact>>().Result;
ListContacts(contacts);
Console.Read();
}
示例11: ReceiveAndDeleteMessage
public static async Task<string> ReceiveAndDeleteMessage()
{
if (_token == null)
_token = GetSasToken();
HttpResponseMessage response = null;
try
{
var httpClient = new HttpClient();
var fullAddress = BaseAddress + QueueName + "/messages/head" + "?timeout=3600000";
httpClient.DefaultRequestHeaders.Add("Authorization", _token);
response = await httpClient.DeleteAsync(fullAddress);
return await response.Content.ReadAsStringAsync();
}
catch (Exception)
{
if (response == null || response.StatusCode != HttpStatusCode.Unauthorized)
return null;
_token = GetSasToken();
return await ReceiveAndDeleteMessage();
}
}
示例12: inline_call_to_invalidate_using_expression_tree_with_custom_action_name_is_correct
public void inline_call_to_invalidate_using_expression_tree_with_custom_action_name_is_correct()
{
var client = new HttpClient(_server);
var result = client.DeleteAsync(_url + "Delete_non_standard_name").Result;
_cache.Verify(s => s.RemoveStartsWith(It.Is<string>(x => x == "inlineinvalidate-getbyid")), Times.Exactly(1));
}
示例13: DeleteTest
public void DeleteTest()
{
Task.Run(async () => {
using (var client = new HttpClient()) {
// add childnode first
var values = new Dictionary<string, string> {
{ "uuid", childNode.selfNode.uuid},
{ "toxid", childNode.selfNode.toxid},
};
long timeStamp = Skynet.Utils.Utils.UnixTimeNow();
client.DefaultRequestHeaders.Add("Skynet-Time", timeStamp + "");
var response = await client.PostAsync(baseUrl + "node/" + testNode.selfNode.uuid
+ "/childNodes", new FormUrlEncodedContent(values));
string responseString = await response.Content.ReadAsStringAsync();
var deleteResponse = await client.DeleteAsync(baseUrl + "node/" + testNode.selfNode.uuid
+ "/childNodes/" + childNode.selfNode.uuid);
string deleteResponseString = await deleteResponse.Content.ReadAsStringAsync();
NodeResponse res = JsonConvert.DeserializeObject<NodeResponse>(deleteResponseString);
Assert.AreEqual(res.statusCode, NodeResponseCode.OK);
Assert.AreEqual(timeStamp, res.time);
Assert.AreEqual(timeStamp, testNode.childNodesModifiedTime);
}
}).GetAwaiter().GetResult();
}
示例14: DeleteGroup
public string DeleteGroup(string id, UserData userData)
{
try
{
client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Timestamp", userData.Timestamp.ToString());
client.DefaultRequestHeaders.Add("Digest", userData.AuthenticationHash);
client.DefaultRequestHeaders.Add("Public-Key", userData.PublicKey);
client.DeleteAsync("http://localhost:3000/contact/" + id)
.ContinueWith(deleteTask =>
{
deleteTask.Result.EnsureSuccessStatusCode();
var result = deleteTask.Result.Content.ReadAsStringAsync();
client.Dispose();
return result;
});
}
catch (Exception ex)
{
throw ex;
}
return null;
}
示例15: GetJsonAsync
public async Task<JObject> GetJsonAsync()
{
Debug.WriteLine(uri);
using (var client = new System.Net.Http.HttpClient())
{
string jsonString = "";
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
if (type == RequestType.GET)
{
jsonString = await client.GetStringAsync(uri);
Debug.WriteLine(jsonString);
}
else if (type == RequestType.POST)
{
CreateJsonContent();
System.Net.Http.HttpResponseMessage response =
await client.PostAsync(uri, new StringContent(obj.ToString(), Encoding.UTF8, "application/json"));
Debug.WriteLine("response : " + response.ToString());
jsonString = await response.Content.ReadAsStringAsync();
Debug.WriteLine(jsonString);
}
else if (type == RequestType.DELETE)
{
System.Net.Http.HttpResponseMessage response = await client.DeleteAsync(uri);
Debug.WriteLine("response : " + response.StatusCode.ToString());
jsonString = await response.Content.ReadAsStringAsync();
}
Debug.WriteLine("jsonstring : " + jsonString);
return JObject.Parse(jsonString);
}
}