when i am posting data from postman it is successfully deleted but i am getting error of method not allowed in .net core controller
i am entering url as per postmans url
can you help me with the right method or let me know what i am doing wrong
Code in asp.net core controller
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Delete( int id,CountryModel collection)
{
//try
//{
// collection.DeleteCountry(collection);
// return RedirectToAction(nameof(Index));
//}
//catch
//{
// return View();
//}
try
{
string message = "";
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://192.168.10.34:81/api/");
//HTTP POST
var postTask = await client.DeleteAsync(client.BaseAddress "Country/" id);
var result = postTask.EnsureSuccessStatusCode();
if (result.IsSuccessStatusCode)
{
RedirectToAction("Index");
}
ModelState.AddModelError(string.Empty, "Server Error. Please contact administrator.");
//collection.Insert(collection);
return RedirectToAction("Index");
}
}
catch (Exception ex)
{
return RedirectToAction("Index"); ;
}
}
**code in web api **
[HttpDelete("{id}")]
public PostResult Delete(int Id)
{
try
{
if (Id != 0)
{
if (CountryModel.DeleteCountry(Id))
{
return new PostResult(true);
}
else
{
return new PostResult(false);
}
}
else
{
return new PostResult(false);
}
}
catch (Exception ex)
{
return new PostResult(false);
}
}
CodePudding user response:
In your ASP.NET Core Controller your Delete is expecting a CountryModel. I think you are not supplying it to the request because you don't use it.
public async Task<ActionResult> Delete(int id, CountryModel collection)
{
}
You must remove it so it doesn't expect it. This is why you get the error of method not allowed. Because it can't find a method without the parameter CountryModel. Your method should look like this:
public async Task<ActionResult> Delete (int id)
{
}
CodePudding user response:
From HttpClient.BaseAddress
Remarks,
When sending a HttpRequestMessage with a relative Uri, the message Uri will be added to the BaseAddress property to create an absolute Uri.
Note that all characters after the right-most "/" in the base URI are excluded when combined with the message URI. See RFC 3986 Uniform Resource Identifier (URI) Generic Syntax specification.
You don't need to append client.BaseAddress
in client.DeleteAsync()
.
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://192.168.10.34:81/api/");
var postTask = await client.DeleteAsync("/Country/" id);
...
}