Web API Service Call Function In Blazor Component

Introduction

The Blazor is one of the best web application development platforms. It's easy to manage the source code and large-scale applications are easy to develop and support. For example, when building a simple mobile contact application the resource layout is indexed. razor Class name is Users. cs, Newtonsoft.Json, System.Net, and System.Net.Http is a reference.

Step 1. Create a new project.

New project

Step 2. Enter the project name.

Project name

Step 3. Add references Newtonsoft.json.

Add references

Step 4. Create a Class User. cs.

namespace EmptyBlazorWebAPI.Pages
{
    public class Users
    {
        public int ID { get; set; }
        public string Username { get; set; }
        public string Mobile { get; set; }
    }
}

Step 5. Import the @using Newtonsoft.Json.

Import

Step 6. Open the index. razor. Create a design and functionality.

@page "/"
@using System.Net;
@using System.Text;

<h1>Hello, Blazor</h1>

<input placeholder="Enter username name" @bind="@Username" />

<input placeholder="Enter Mobile Number" @bind="@Mobile" />

<button @onclick="Post">Add</button>

@code
{
    string Username;
    string Mobile;
    void Post()
    {
        Users objProduct = new Users();
        objProduct.Username = Username;
        objProduct.Mobile = Mobile;
        string json = JsonConvert.SerializeObject(objProduct);

        var baseAddress = "http://localhost:2514/api/values/GetMobileInsert?Username=" + Username + "&Mobile=" + Mobile + "";

        var http = (HttpWebRequest)WebRequest.Create(new Uri(baseAddress));
        http.Accept = "application/json";
        http.ContentType = "application/json";
        http.Method = "POST";

        string parsedContent = json;
        ASCIIEncoding encoding = new ASCIIEncoding();
        Byte[] bytes = encoding.GetBytes(parsedContent);

        Stream newStream = http.GetRequestStream();
        newStream.Write(bytes, 0, bytes.Length);
        newStream.Close();

        var response = http.GetResponse();

        var stream = response.GetResponseStream();
    }
}

Sample output

Output

Summary

C# developer is easy to handle on Blazor application development. I have implemented the "Post" option. Try to carry out the "Get", "Post" and "Delete" options. I hope this method helps you to make API Web service calls in Blazor application development.


Similar Articles