我已经为这个问题苦苦挣扎了一段时间,阅读一堆诸如此类的文章:
MSDN ASP.NET Core RESTfull Web API
并且没有掌握正确的方法。
在我当前的项目中,我有:
- 我认为的表单:
<form method="delete" asp-route="ProductCatalogSingle">
<input hidden type="number" name="Id" value="@Model.Id" />
<input type="submit" class="btn btn-dark" value="Delete" />
</form>
- 哪些人必须向我的操作发送删除请求:
// Controller have [Route("product-catalog")] attribute
[HttpDelete("product",Name = "ProductCatalogSingle")]
public async Task<IactionResult> DeleteSingleItem(int id)
{
// business-logic part responsible for data managment
await logic.RemoveDataModelAsync(new ProductCatalog { Id = id });
return RedirectToRoute("ProductCatalogAll");
}
// other action with same route,but different method
[HttpGet("product",Name = "ProductCatalogSingle")]
public async Task<IactionResult> SingleItem(int id)
{...}
在默认设置下,它不起作用-而是加载“获取操作”。
所以我尝试了很多事情:
- 使用同时具有
"/product-catalog/product"
和"@Url.Link("ProductCatalogSingle",null)"
而不是url
的Fetch API:
@section scripts{
<script>
document.forms[0].onsubmit = () => {
let formData = new FormData(document.forms[0]);
fetch(url,{
method: "DELETE",body: new URLSearchParams(formData)
})
.then(() => {
alert('Deleted using Fetch');
});
return true;
};
</script>
我收到警报通知,但请求未发送。
- 使用非结构化AJAX:
@section scripts{
<script src="~/lib/jquery-ajax-unobtrusive/jquery.unobtrusive-ajax.js"></script>
}
<form method="delete" asp-route="ProductCatalogSingle" data-ajax="true" data-ajax-method="delete">
<input hidden type="number" name="productId" value="@item.ProductId" />
<input type="submit" class="btn btn-dark" value="Delete" />
</form>
- 纯JQuery AJAX
@section scripts{
<script>
$(function () {
$('#submit').on('click',function (evt) {
evt.preventDefault();
$.ajax({
type: "DELETE",url: '/product-catalog/product?id=4001'
});
});
});
</script>
- 更改IIS Express服务器变量,例如IIS Express FAQ状态
<add name="ExtensionlessUrl-Integrated-4.0" ... verb="GET,HEAD,POST,DEBUG,PUT,DELETE"
这些都不起作用。