简体   繁体   English

如何在客户端(blazor webassembly)调用create webapi(blazor server app)

[英]how to call create webapi(blazor server app) in client side(blazor webassembly)

I create a blazor server app project and I use a webapi built in crud api framework我创建了一个 blazor 服务器应用程序项目,我使用了一个内置在 crud api 框架中的 webapi

EmpsController.cs 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);
        }

and then I create a blazor webassembly project and create a razor component然后我创建一个 blazor webassembly 项目并创建一个 razor 组件

Registration.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");
            }
        }
    }
}

server side(blazor server app project)服务器端(Blazor 服务器应用程序项目)

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

client side(webassembly project)客户端(webassembly项目)

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

I am trying to create record but record not created?我正在尝试创建记录但未创建记录?

what I am missing?我缺少什么?

which place need to correction?哪些地方需要修正?

Since we don't have any information about the model in the POST so I'm assuming the property names using Delphi notation.由于我们在 POST 中没有关于 model 的任何信息,因此我假设属性名称使用 Delphi 表示法。 Blazor uses the new System.Text.Json for serialization and if not set it will try to parse the data in case sensitive form. Blazor 使用新的System.Text.Json进行序列化,如果未设置,它将尝试以区分大小写的形式解析数据。 (The PostAsJsonAsync<T> also uses the new api in the background) This could be one possible source of the issue. PostAsJsonAsync<T>还在后台使用新的 api)这可能是问题的一个可能来源。

To fix this you can pass a settings to the serializer.要解决此问题,您可以将设置传递给序列化程序。 For example:例如:

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

From the information provided this is the only issue I could think of.从提供的信息来看,这是我唯一能想到的问题。 You could also try to add input validation like FluentValidator .您也可以尝试添加像FluentValidator这样的输入验证。

You should not create the HttpClient in that way, you need to inject in the same way the FetchData sample does in the basic sample app https://gist.github.com/SteveSandersonMS/7c5e80ebf7f238505f1281f550666600您不应该以这种方式创建HttpClient ,您需要以与基本示例应用程序https://gist.github.com/SteveSandersonMS/7c5e80ebf7f238505f1281f550666600中的FetchData示例相同的方式注入

Try addding尝试添加

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

at the top of your page.在页面顶部。 Change your Create method as follows:如下更改您的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");
            }
        }
    }

I've used YourExpectedResult as the type you expect as your sample does not say what type you're deserializing to.我使用YourExpectedResult作为您期望的类型,因为您的示例没有说明您要反序列化的类型。

More info: https://learn.microsoft.com/en-us/as.net/core/blazor/call-web-api?view=as.netcore-3.1更多信息: https://learn.microsoft.com/en-us/as.net/core/blazor/call-web-api?view=as.netcore-3.1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 blazor webassembly 应用程序(客户端)中调用 blazor 服务器应用程序(登录 webapi) - how to call blazor server app(login webapi) in blazor webassembly app(client side) 没有托管的 Blazor WebAssembly 作为客户端与 .Net Core WebAPI 作为服务器端交互 - Blazor WebAssembly without hosted act as client side interact with .Net Core WebAPI as server side 如何在发布服务器项目而不是客户端的 Azure DevOps 上为 Blazor WebAssembly 托管应用程序创建构建管道? - How to create a build pipeline for Blazor WebAssembly Hosted app on Azure DevOps that publishes the server project not the client? 如何在 blazor webassembly 应用程序中获取服务器 url? - How to get the server url in blazor webassembly app? 如何使用 blazor 客户端应用程序在服务器上创建新文件? - How to create a new file on the server with blazor client-side application? 从 Blazor WebAssembly 客户端项目中的 GetFromJsonAsync 调用接收 Blazor 服务器项目中 API 方法中的参数 - Receiving parameter in API method in Blazor Server project from GetFromJsonAsync call in Blazor WebAssembly Client project 如何在获取参数集时调用 Blazor 服务器端应用程序中的方法 - How to call a method in Blazor Server Side App on get set of a parameter Blazor WebAssembly 阻止 WebApi AllowAnonymous - Blazor WebAssembly blocks WebApi AllowAnonymous Blazor Webassembly 应用程序显示来自服务器的图像 - Blazor Webassembly App display image from server 如何在 Blazor 客户端应用程序的服务中调用 HttpClient - How Do I Call HttpClient in Service for a Blazor Client-Side App
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM