Rahul Patil
Rahul Patil

Reputation: 142

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

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

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

server side(blazor server app project)

https://i.sstatic.net/t6GVI.png

client side(webassembly project)

https://i.sstatic.net/JZxua.png

I am trying to create record but record not created?

what I am missing?

which place need to correction?

Upvotes: 1

Views: 2026

Answers (2)

Quango
Quango

Reputation: 13468

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

Try addding

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

at the top of your page. Change your Create method as follows:

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.

More info: https://learn.microsoft.com/en-us/aspnet/core/blazor/call-web-api?view=aspnetcore-3.1

Upvotes: 1

Zsolt Bendes
Zsolt Bendes

Reputation: 2589

Since we don't have any information about the model in the POST so I'm assuming the property names using Delphi notation. Blazor uses the new System.Text.Json for serialization and if not set it will try to parse the data in case sensitive form. (The PostAsJsonAsync<T> also uses the new api in the background) This could be one possible source of the issue.

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.

Upvotes: 1

Related Questions