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