Code does not continue after the return ok() from web api

huangapple go评论68阅读模式
英文:

Code does not continue after the return ok() from web api

问题

Here is the translated content you requested:

**你好,我正在构建一个简单的程序,只是为了学习 asp webapi 和 blazor,我的 post 函数在 postman 上测试过,以下是您观察的代码:**

```csharp
[HttpPost]
[Route("addSingleProduct")]
public IActionResult Post([FromBody] ProductModel product)
{
    try
    {
        if (product == null)
        {
            return BadRequest();
        }
        if (product != null)
        {
            _conn.Open();
            string query = "INSERT INTO Product VALUES (@ProdName, @ProdPrice,@ProdDesc,@ProdImg,@CatgId,@ProdFam)";
            using (Def.cmd = new SqlCommand(query, _conn))
            {
                Def.cmd.Parameters.AddWithValue("@ProdName", product.ProdName);
                Def.cmd.Parameters.AddWithValue("@ProdPrice", product.ProdPrice);
                Def.cmd.Parameters.AddWithValue("@ProdDesc", product.ProdDesc);
                Def.cmd.Parameters.AddWithValue("@ProdImg", product.ProdImg);
                Def.cmd.Parameters.AddWithValue("@CatgId", product.CatgId);
                Def.cmd.Parameters.AddWithValue("@ProdFam", product.ProdFam);

                int rowsAffected = Def.cmd.ExecuteNonQuery();
                if (rowsAffected == 0)
                {
                    _conn.Close();
                    return StatusCode(StatusCodes.Status500InternalServerError, "插入产品失败");
                }
            }
            _conn.Close();
        }
        return Ok();
    }
    catch (Exception ex)
    {
        _conn.Close();
        Console.WriteLine(ex.Message);
        return StatusCode(StatusCodes.Status500InternalServerError, "插入产品失败");
    }
}

在我的 Blazor 应用中,我正在等待响应以将值放入布尔值中,以便向用户显示产品已添加:

@if(isadded==true){
    <h1>产品已添加</h1>
}else{
    <h1>产品未添加</h1>
}

@code {
    private bool isadded;
    [Inject]
    private GetProductsService productService { get; set; }

    private ProductModel product = new ProductModel();

    protected async Task<bool> AddNewProduct()
    {
        try
        {
            HttpResponseMessage response = await productService.AddProduct(product);
            if (response.IsSuccessStatusCode)
            {
                isadded = true;
            }
            else
            {
                string responseContent = await response.Content.ReadAsStringAsync();
                Console.WriteLine($"添加产品失败,状态码 {response.StatusCode}:{responseContent}");
                isadded  = false;
            }
            return isadded;
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            return false;
        }
    }
}

这是我制作 API 调用的服务:

public async Task<HttpResponseMessage> AddProduct(ProductModel product)
{
    return await _httpClient.PostAsJsonAsync("api/Product/AddSingleProduct", product);          
}

代码运行顺利,模型被发送到 API 并插入到数据库中,但当它返回 Ok() 时,什么也不发生,调试停止,所以我无法告诉用户产品已添加。


Please note that I've translated the code comments and error messages as well. If you have any specific questions or need further assistance, please feel free to ask.

<details>
<summary>英文:</summary>

   **Hello im building a simple program just to learn asp webapi and blazor, my post function  is working fine it was tested on postman here is my code for your observation : **
    [HttpPost]
    [Route(&quot;addSingleProduct&quot;)]
    public IActionResult Post([FromBody] ProductModel product)
    {
        try
        {
            if (product == null)
            {
                return BadRequest();
            }
            if (product != null)
            {
                _conn.Open();
                string query = &quot;INSERT INTO Product VALUES (@ProdName, @ProdPrice,@ProdDesc,@ProdImg,@CatgId,@ProdFam)&quot;;
                using (Def.cmd = new SqlCommand(query,_conn))
                {
                    Def.cmd.Parameters.AddWithValue(&quot;@ProdName&quot;, product.ProdName);
                    Def.cmd.Parameters.AddWithValue(&quot;@ProdPrice&quot;, product.ProdPrice);
                    Def.cmd.Parameters.AddWithValue(&quot;@ProdDesc&quot;, product.ProdDesc);
                    Def.cmd.Parameters.AddWithValue(&quot;@ProdImg&quot;, product.ProdImg);
                    Def.cmd.Parameters.AddWithValue(&quot;@CatgId&quot;, product.CatgId);
                    Def.cmd.Parameters.AddWithValue(&quot;@ProdFam&quot;, product.ProdFam);

                    //Def.cmd.ExecuteNonQuery();
                    int rowsAffected = Def.cmd.ExecuteNonQuery();
                    if (rowsAffected == 0)
                    {
                        _conn.Close();
                        return StatusCode(StatusCodes.Status500InternalServerError, &quot;Failed to insert product&quot;);
                    }
                }
                _conn.Close();                   
            }
            return Ok();
        }
        catch(Exception ex)
        {
            _conn.Close();
            Console.WriteLine(ex.Message);
            return StatusCode(StatusCodes.Status500InternalServerError, &quot;Failed to insert product&quot;);
        }
    }
**in my Blazor app im awaiting the response to place the value in a boolean so i can show the user that the product was added **

@if(isadded==true){
<h1>Product was added</h1>
}else{
<h1>Product was not added</h1>
}

@code {
private bool isadded;
[Inject]
private GetProductsService productService { get; set; }

private ProductModel product = new ProductModel();

protected async Task&lt;bool&gt; AddNewProduct()
{
    try
    {
        HttpResponseMessage response = await productService.AddProduct(product);
        if (response.IsSuccessStatusCode)
        {
            isadded = true;
        }
        else
        {
            string responseContent = await response.Content.ReadAsStringAsync();
            Console.WriteLine($&quot;AddProduct failed with status code {response.StatusCode}: {responseContent}&quot;);
            isadded  = false;
        }
        return isadded;
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
        return false;
    }
}

}

**And here is my service where i make the api call**

public async Task<HttpResponseMessage> AddProduct(ProductModel product)
{
return await _httpClient.PostAsJsonAsync("api/Product/AddSingleProduct", product);
}

**The code runs smoothly the model is being sent to the api and inserted in the database but when it hits return ok() nothing happens and the debugging stops so im not able to tell the user that the product was added **

</details>


# 答案1
**得分**: 0

以下是翻译好的内容:

似乎问题出在您的 Blazor 组件中 `isadded` 布尔值未能正确更新。

在您的代码中,您异步调用了 `AddNewProduct()` 方法,但在调用它时没有等待结果。这意味着 `isadded` 值可能在代码执行时未能更新,导致它始终显示 "产品未添加"。

为了解决这个问题,您应该在调用 AddNewProduct() 方法时等待它的结果:

```csharp
protected async Task AddNewProduct()
{
    isadded = await productService.AddProduct(product);

    StateHasChanged();
}

在您的 GetProductsService 类中,您应该修改 AddProduct() 方法,使其返回一个布尔值而不是 HttpResponseMessage:

public async Task<bool> AddProduct(ProductModel product)
{
    HttpResponseMessage response = await _httpClient.PostAsJsonAsync("api/Product/AddSingleProduct", product);
    return response.IsSuccessStatusCode;
}

通过这样做,您返回一个布尔值,指示产品是否已添加。

然后,在您的 Blazor 组件中,您可以更新 AddNewProduct() 方法以使用返回的布尔值:

protected async Task AddNewProduct()
{
    isadded = await productService.AddProduct(product);

    StateHasChanged();
}

通过这些更改,isadded 值应该得到正确更新,UI 应该根据产品是否已添加来显示正确的消息。

英文:

It seems that the issue is with the isadded boolean value not being updated properly in your Blazor component.

In your code, you're calling the AddNewProduct() method asynchronously, but you're not awaiting the result when calling it. This means that the isadded value might not be updated by the time the code is executed, causing it to always show "Product was not added".

To fix this, you should await the AddNewProduct() method when calling it:

protected async Task AddNewProduct()
{
    isadded = await productService.AddProduct(product);

    StateHasChanged();
}

In your GetProductsService class, you should modify the AddProduct() method to return a bool value instead of an HttpResponseMessage:

public async Task&lt;bool&gt; AddProduct(ProductModel product)
{
    HttpResponseMessage response = await _httpClient.PostAsJsonAsync(&quot;api/Product/AddSingleProduct&quot;, product);          
    return response.IsSuccessStatusCode;
}

By doing this, you're returning a boolean value indicating whether the product was added or not.

Then, in your Blazor component, you can update the AddNewProduct() method to use the returned boolean value:

protected async Task AddNewProduct()
{
    isadded = await productService.AddProduct(product);

    StateHasChanged();
}

With these changes, the isadded value should be properly updated and the UI should display the correct message based on whether the product was added or not.

huangapple
  • 本文由 发表于 2023年4月13日 18:34:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76004419.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定