首页 > 解决方案 > 如何在客户端(blazor webassembly)调用创建 webapi(blazor 服务器应用程序)

问题描述

我创建了一个 blazor 服务器应用程序项目,并使用了一个内置于 crud api 框架中的 webapi

EmpsController.cs

    [Route("api/[controller]")]
    [ApiController]
    public class EmpsController : ControllerBase
    {
        private readonly sqldbcontext _context;

        public EmpsController(sqldbcontext context)
        {
            _context = context;
        }

        // GET: api/Emps
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Emp>>> Getemps()
        {
            return await _context.emps.ToListAsync();
        }

       [HttpPost]
        public async Task<ActionResult<Emp>> PostEmp(Emp emp) //I want to call this webapi in clientside(webassembly app)
        {
            _context.emps.Add(emp);
            await _context.SaveChangesAsync();

            return CreatedAtAction("GetEmp", new { id = emp.empid }, emp);
        }

然后我创建了一个 blazor webassembly 项目并创建了一个 razor 组件

注册.razor

@page "/registration"
@using Newtonsoft.Json;
@inject NavigationManager navigationManager
<h3>Registration</h3>
@using CrudBlazorServerApp.Data

<div>
    UserName: <input type="text" id="txtusername" placeholder="Enter Your UserName" @bind="@username" required /><br />
    Address: <input type="text" id="txtempaddress" placeholder="Enter Your Address" @bind="@address" required /><br />
    Password:  <input type="text" id="txtpassword" placeholder="Enter Your Password" @bind="@password" required /><br />
    Country: <input type="text" id="txtcountry" placeholder="Enter Your Country" @bind="@country" required /><br />
    <button @onclick="Create">Submit</button><br /><br /><br /><br />
    <a href="https://localhost:44399/">Click Here For Login</a>
</div>

@code {
    string username = "";
    string address = "";
    string password = "";
    string country = "";

    Emp empList = new Emp();

    protected async Task Create()
    {
        var client = new HttpClient();

        HttpResponseMessage response = await client.PostAsJsonAsync<Emp>("https://localhost:44333/api/emps",empList);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Add("Accept", "application/json");
        @if (response.IsSuccessStatusCode)
        {
            var returnuserdata = await response.Content.ReadAsStringAsync();
            var userdata = JsonConvert.DeserializeObject(returnuserdata);
            if (userdata != null)
            {
                navigationManager.NavigateTo("/login");
            }
            else
            {
                navigationManager.NavigateTo("/registration");
            }
        }
    }
}

服务器端(Blazor 服务器应用程序项目)

https://i.stack.imgur.com/t6GVI.png

客户端(webassembly项目)

https://i.stack.imgur.com/JZxua.png

我正在尝试创建记录但未创建记录?

我错过了什么?

哪些地方需要改正?

标签: c#blazorblazor-server-sideblazor-client-sideblazor-webassembly

解决方案


您不应该HttpClient以这种方式创建,您需要以与基本示例应用程序中 的FetchData示例相同的方式注入https://gist.github.com/SteveSandersonMS/7c5e80ebf7f238505f1281f550666600

尝试添加

@using System.Net.Http
@inject HttpClient client;

在您的页面顶部。改变你的Create方法如下:

protected async Task Create()
  {
      HttpResponseMessage response = await client.PostAsJsonAsync<Emp>("https://localhost:44333/api/emps",empList);
      @if (response.IsSuccessStatusCode)
      {
          var userdata = response.Content.ReadFromJsonAsync<YourExpectedResult>();
            if (userdata != null)
            {
                navigationManager.NavigateTo("/login");
            }
            else
            {
                navigationManager.NavigateTo("/registration");
            }
        }
    }

我使用YourExpectedResult了您期望的类型,因为您的示例没有说明您要反序列化的类型。

更多信息:https ://docs.microsoft.com/en-us/aspnet/core/blazor/call-web-api?view=aspnetcore-3.1


推荐阅读