如何在客户端(blazor webassembly)中调用create webapi(blazor服务器应用)

时间:2020-08-31 14:06:18

标签: c# blazor blazor-server-side blazor-client-side blazor-webassembly

我创建了一个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项目并创建一个剃刀组件

Registration.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

客户端(网络组装项目)

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

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

我想念什么?

哪个地方需要更正?

2 个答案:

答案 0 :(得分:0)

由于POST中没有有关模型的任何信息,因此我假设属性名称使用Delphi表示法。 Blazor使用新的System.Text.Json进行序列化,如果未设置,它将尝试以区分大小写的形式解析数据。 (PostAsJsonAsync<T>还在后台使用新的api) 这可能是造成此问题的原因之一。

要解决此问题,您可以将设置传递给串行器。例如:

var serializeOptions = new JsonSerializerOptions
{
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
};
var jsonString = JsonSerializer.Serialize(empDetails, serializeOptions);

根据提供的信息,这是我唯一想到的问题。您也可以尝试添加输入验证,例如FluentValidator

答案 1 :(得分:0)

您不应该以这种方式创建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