how to make Blazor HTTP Get JSON ASYNC request?
I don't think this is a Blazor issue, I assume you're using the Blazor WebAssembly Hosted template?
If you try and load your API endpoint by navigating to it in a browser what do you see? I'm going to guess it's a 404 not found or a 500 error?
I think the issue is how you've defined the route on your API controller. Try the following setup.
[ApiController]
[Route("[controller]")]
public class EmployeeController : ControllerBase
{
EmployeeRepository objemployee = new EmployeeRepository();
[HttpGet]
public IEnumerable<Employee> Index()
{
return objemployee.GetAllEmployees().ToArray();
}
}
Then make a call employees = await Http.GetJsonAsync<Employee[]>("Employee");
, if all goes well you should get your list of employees back.
Send a parameter with Http.GetJsonAsync
HttpGet
passes parameters through the URL,so it's as easy as adding ?userid=value
to the URL like this:
myTrades = await Http.GetJsonAsync<ItemForTrade[]>("api/Trading/GetTradesForUser?userid=" + userid);
how to make HTTP GET specific data in Blazor?
The client expect another response from the server. The client side expect a array (a sort list) and the server side returned a single object.
I would expect this:
private UserProfile forecasts;
protected override async Task OnInitializedAsync()
{
forecasts = await Http.GetFromJsonAsync<UserProfile>("Authentication/ed131c76-4a3a-4626-aec5-3db534f14a30/amrita");
}
The properties need to match to get the data in the object of UserProfile. Otherwise some of the properties will be empty.
A good practice would be to create a shared project with the client and the server side with the possible responses and requests. Then you should have a less chance to get a mismatch.
How to covert Json result into string in Blazor WebAssembly?
OK, I can see a few problems.
On the Server:
[HttpGet]
[Route("UserId")]
public async Task<ActionResult<ApplicationUser>> GetUserId(string Username) // A
{
var user = await userManager.FindByNameAsync(Username);
if (user == null) // B
return StatusCode(StatusCodes.Status500InternalServerError, new Response { Status = "Error", Message = "User not exist" });
var result = await userManager.GetUserIdAsync(user);
return new JsonResult(result);
}
First, your return type here is Task<ActionResult<ApplicationUser>>
. ApplicationUser is tied to the backend Identity library, you can't and shouldn't use it for a DTO.
And you don't, in the end you have return new JsonResult(result);
which is OK when you change the return type to just Task<ActionResult>
.
On the client:
//user = await Http.GetFromJsonAsync<userName>("Authentication/UserId?Username=" + Username);
var userId = await Http.GetFromJsonAsync<string>("Authentication/UserId?Username=" + Username);
The endpoint returns a simple string. Json does not know about 'UserName' or anything else.
//string Id = System.Text.Json.JsonSerializer.Serialize(user); -- use UserId
You are serializing the Id (again) here, making it almost certainly invalid for an URL. So just skip that.
HttpClient.GetJsonAsync Not found. (blazor server)
The method signature is the following:
public static async Task<T> GetJsonAsync<T>(this HttpClient httpClient, string requestUri);
So it is a generic method and you will have to include the type argument in the call.
In your case, this should look like this:
HttpClient client = new HttpClient();
var user = await client.GetJsonAsync<User>($"{BaseUrl}Get-User/{Id}");
This will already deserialize the JSON response to the User
type.
Note that you will need a using for the Microsoft.AspNetCore.Components
namespace in order for this extension method to appear.
Related Topics
How to Read Request Body in an ASP.NET Core Webapi Controller
Add Header and Footer for Pdf Using Itextsharp
How to Extract Custom Header Value in Web API Message Handler
Unit Test a Method That Returns a Void
Clearing a Textbox Leaves an Invisible Character
How to Download a File from a Url in C#
Restsharp Post Request - Body With X-Www-Form-Urlencoded Values
How to Set a Cookie on Httpclient'S Httprequestmessage
How to Submit Disabled Input in ASP.NET MVC
Multidimensional Array from a Txt File
Use Latest Version of Internet Explorer in the Webbrowser Control
How to Convert English Digits to Arabic Digits
Check If Combobox Value Is Empty
Moq - Non-Overridable Members May Not Be Used in Setup/Verification Expressions
Why Am I Getting Error Cs0246: the Type or Namespace Name Could Not Be Found