locked
how to call create webapi(blazor server app) in client side(blazor webassembly) RRS feed

  • Question

  • User-91993069 posted

    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)

    client side(webassembly project)

    I am trying to create record but record not created?

    what I am missing?

    which place need to correction?

    Monday, August 31, 2020 12:06 PM

All replies

  • User475983607 posted

    What exactly is the problem?  Does the HTTP request reach the POST action?  Are there any errors?  

    The following is an example that shows how to use the HttpClient to call Web API. 

    Register the HttpClient service in Program.cs.

        public class Program
        {
            public static async Task Main(string[] args)
            {
                var builder = WebAssemblyHostBuilder.CreateDefault(args);
                builder.RootComponents.Add<App>("app");
    
                builder.Services.AddSingleton(sp => new HttpClient { BaseAddress = new Uri("https://localhost:44379") });
    
                await builder.Build().RunAsync();
            }
        }

    Inject the server and call the Web API URL.

    @page "/postform"
    @inject HttpClient Http
    <h3>Registration</h3>
    
    <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="SaveRegistration">Submit</button><br /><br /><br /><br />
        <a href="https://localhost:44399/">Click Here For Login</a>
    </div>
    
    
    <div>
        @jsonResponse
    </div>
    
    @code {
        private string username = string.Empty;
        private string address = string.Empty;
        private string password = string.Empty;
        private string country = string.Empty;
        private string jsonResponse = string.Empty;
    
        private async Task SaveRegistration()
        {
            Employee employee = new Employee()
            {
                Username = username,
                Address = address,
                Country = country,
                Password = password,
            };
            HttpResponseMessage response = await Http.PostAsJsonAsync("api/Account", employee);
            jsonResponse = await response.Content.ReadAsStringAsync();
        }
    
        public class Employee
        {
            public int Id { get; set; }
            public string Username { get; set; }
            public string Password { get; set; }
            public string Address { get; set; }
            public string Country { get; set; }
        }
    
    }
    

    It's uncommon to pass an entity.  Typically, a model is passed to Web API and Web API maps the model to an Entity. 

    Web API.  

        [Route("api/[controller]")]
        [ApiController]
        public class Account : ControllerBase
        {
            private readonly List<Employee> items;
            private readonly ILogger<Account> _logger;
            public Account(ILogger<Account> logger)
            {
                logger = _logger;
                items = PopulateEmployees();
            }
    
            [HttpGet]
            public ActionResult<List<Employee>> Get()
            {
                return items;
            }
    
            [HttpPost]
            public ActionResult<Employee> Post(Employee Employee)
            {
                return Employee;
            }
    
            private List<Employee> PopulateEmployees()
            {
                return new List<Employee>()
                {
                    new Employee()
                    {
                         Id = 1,
                         Username = "Hello",
                         Password = "World",
                         Country = "USA",
                         Address = "123 East"
                    },
                    new Employee()
                    {
                         Id = 2,
                         Username = "Foo",
                         Password = "Bar",
                         Country = "USA",
                         Address = "456 West"
                    }
                };
            }
        }

    Keep in mind, if the Web API service is in another project then you must enable CORS in the Web API startup.cs file.

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        { 
            options.AddDefaultPolicy(
            builder =>
            {
                builder.WithOrigins("https://localhost:44331", "https://localhost:44301")
                .AllowAnyHeader()
                .AllowAnyMethod()
                .AllowCredentials();
                });
            });
    
            services.AddControllers()
                .AddJsonOptions(options => options.JsonSerializerOptions.IgnoreNullValues = true);
        }

    Monday, August 31, 2020 2:51 PM
  • User-91993069 posted

    Hello mhebhard

    thanks for your time

    but still I am facing issue means record is not created

    see my project hierarchy

    see my blazor server app project

    namespace CrudBlazorServerApp.Controllers
    {
        [Route("api/[controller]")]
        [ApiController]
        public class EmpsController : ControllerBase
        {
            private readonly List<Emp> items;
            private readonly ILogger<Emp> _logger;
            private readonly sqldbcontext _context;
    
            public EmpsController(ILogger<Emp> logger, sqldbcontext context)
            {
                logger = _logger;
                _context = context;
            }
    
            [HttpPost]
            public ActionResult<Emp> Post(Emp Employee) //debugger not come here
            {
                return Employee;
            }

    see output of my blazor server app project

    blazor webassembly project

    @page "/registration"
    @using Newtonsoft.Json.Serialization;
    @inject NavigationManager navigationManager
    <h3>Registration</h3>
    @using CrudBlazorServerApp.Data
    @using System.Net.Http.Headers;
    @using System.Web;
    @using System.Text.Json
    @using Newtonsoft.Json
    @inject HttpClient Http
    
    <div>
        @jsonResponse
    </div>
    
    <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{
    
        private string username = string.Empty;
        private string address = string.Empty;
        private string password = string.Empty;
        private string country = string.Empty;
        private string jsonResponse = string.Empty;
    
        private async Task Create()
        {
            Emp employee = new Emp()
            {
                username = username,
                empaddress = address,
                country = country,
                password = password,
            };
            HttpResponseMessage response = await Http.PostAsJsonAsync<Emp>("https://localhost:44333/api/emps", employee);
            jsonResponse = await response.Content.ReadAsStringAsync();
        }
    
        public class Emp
        {
            public int empid { get; set; }
            public string username { get; set; }
            public string empaddress { get; set; }
            public string password { get; set; }
            public string country { get; set; }
    
        }
    }

    see output of blazor webassembly client side project console log

    I am trying to hit the postapi using postman tool but not hit the create webapi

    can you please guide which place I am doing wrong?

    Tuesday, September 1, 2020 5:53 AM
  • User-91993069 posted

    Hello mgebhard

    I think main issue is post webapi is not hit that is the reason record not created

    Tuesday, September 1, 2020 6:34 AM
  • User-91993069 posted

    Hello mgebhard

    help

    Tuesday, September 1, 2020 8:42 AM
  • User475983607 posted

    According to the screensshot you are not using PostMan correctly.  The post parameters are JSON formatted located in the body.  See PostMan support for assistance using the tool. https://dotnettutorials.net/lesson/how-to-use-postman-to-test-web-api/

    The Dev Tools screen shot shows a 204 (No Content) response which mean an action was invoked but no content was returned.  I'm not sure what state your code is in so it's hard to figure out what you're doing.

    Tuesday, September 1, 2020 10:08 AM
  • User-91993069 posted

    main issue is webapi not hit why still i am not able to find the solution

    Tuesday, September 1, 2020 10:47 AM
  • User-91993069 posted

    yes you r right

    but  what is solution?

    Tuesday, September 1, 2020 10:54 AM