簡體   English   中英

如何使 PUT 從 ASP.NET MVC 到 ASP.NET 核心 Web ZDB974238714CA8A44A7CE1D0?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM