[英]How to make a PUT request from ASP.NET core mvc to Web API in asp.net core?
[英]How to make PUT from ASP.NET MVC to ASP.NET Core Web API?
我在使用 Web API 的 put 方法時遇到問題。 我正在使用 ASP.NET MVC 內的 Kendo UI Jquery,它必須通過 API 進行 PUT。
請指導我我做錯了什么,最后也是錯誤代碼。
這是我到目前為止所嘗試的:
API controller:
[HttpPut] //It never reaches here
[Route("api/Update")]
public async Task<IActionResult> Update(Guid id, UpdateProductCommand command)
{
if (id != command.Id)
{
return BadRequest();
}
return Ok(await _mediator.Send(command));
}
ASP.NET MVC controller:
public ActionResult Update(Guid id, [FromBody]Product product)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://localhost:44393");
var json = JsonConvert.SerializeObject(product);
var contentData = new StringContent(json, Encoding.UTF8, "application/json");
var response = client.PutAsync("/api/Product", contentData);
var result = response.Result;
if (result.IsSuccessStatusCode)
{
return RedirectToAction("Index");
}
}
return View(product);
}
使用 Kendo UI 查看:
<script>
//----------TRANSPORT -------------------//
var dataSource = new kendo.data.DataSource({
batch: false,
transport: {
read: {
url: "https://localhost:44393/api/Product",
dataType: "json"
},
update: {
url: "@Url.Action("Update", "Home")",
dataType: "json",
},
create: {
url: "@Url.Action("Create", "Home")",
dataType: "json",
contentType: "application/json",
type: "POST"
},
destroy: {
url: "@Url.Action("Delete", "Home")",
dataType: "json",
},
},
pageSize: 5,
schema: {
model: {
id: "id",
fields: {
id: { editable: false, nullable: true },
productName: { type: "string", editable: true },
prouctSKU: { type: "string", editable: true },
productType: { type: "string", editable: true },
}
}
}
});
錯誤:
jquery.min.js:4 GET https://localhost:44385/Home/Update?id=1e8332f1-ae69-4997-b851-08d9ae&uuct=de&productType=string
您需要告訴您的組件發出PUT
請求,否則它將默認為GET
。 根據文檔,您應該指定請求的type
。 例如:
update: {
url: "@Url.Action("Update", "Home")",
dataType: "json",
type: "PUT" //<---- Add this
},
在您的 MVC Controller 中,您在非async
方法中使用PutAsync
。 將您的 Action 更改為async
方法,將ActionResult
更改為async Task<ActionResult>
並在調用PutAsync
時使用await
關鍵字。
或者,如果您不想將方法更改為async
方法,請將調用client.PutAsync
更改為client.Put
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.