I have a good, working, webAPI, that works fine from Postman and 2 other dev type clients, however, I cannot get it to take data from a Blazor WASM client (.Net8). I hit the endpoint route (as per the API’s logging system) just fine, but can’t figure out why one particular field is always reported as empty, even when it’s not (the first parameter, so the other fields may be affected).
I thought it was case sensitivity, as the API does have camel-case parameters, so I changed the Blazor app to ensure the fields matched exactly. I added some debugging points, one that prints out the json data being sent to the API, and it’s 100% perfect! (I checked it repeatedly, and there’s no typos or anything like that and it’s perfectly formatted JSON).
While I have access to the API code, it’s already in use, so changes to it (there’s nothing wrong with it) are both unnecessary and disruptive. (like I said, ONLY the Blazor WASM client cannot seem to send correct data to it).
Ok – the current error message is: ‘textContent’ cannot be null or empty. so I am focusing on why this parameter is being ignored or what-have-you (it’s not the form data nor the jsonSerializer)
Here’s the TextToAudioService.cs file (that does the actual posting to the web api):
using System;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace TextToAudioClient.Services
{
public class TextToAudioService
{
private readonly HttpClient _httpClient;
private readonly JsonSerializerOptions _jsonOptions;
public TextToAudioService(HttpClient httpClient)
{
_httpClient = httpClient;
_jsonOptions = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = true
};
}
public async Task<string> ConvertTextToAudioAsync(string textContent, string outputFileNameNoExt, string audioFormat = "mp3", string voice = "echo", double speed = 0.9)
{
try
{
var requestData = new ConvertTextToAudioRequest
{
TextContent = textContent,
OutputFileNameNoExt = outputFileNameNoExt,
AudioFormat = audioFormat,
Voice = voice,
Speed = speed
};
var jsonContent = JsonSerializer.Serialize(requestData, _jsonOptions);
Console.WriteLine($"Request JSON: {jsonContent}"); // Debug logging - JSON is 100% perfect!
//this is the suspicious part - This SHOULD work! (stumped)
var httpContent = new StringContent(jsonContent, Encoding.UTF8, "application/json");
// triple checked the path here - it works since the error log wouldn't report
var response = await _httpClient.PostAsync("api/v1/texttoaudio/convertfrombody", httpContent);
response.EnsureSuccessStatusCode();
// never get to this part since I get 400 error
var audioUrl = await response.Content.ReadAsStringAsync();
return audioUrl;
}
catch (HttpRequestException httpRequestException)
{
// the error is always: 2024-06-03 02:05:33.073 -04:00 [ERR] 'textContent' cannot be null or empty.
Console.WriteLine($"HTTP Request Error: {httpRequestException.Message}");
throw new ApplicationException("An error occurred while processing your request.", httpRequestException);
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
throw new ApplicationException("An unexpected error occurred.", ex);
}
}
}
public class ConvertTextToAudioRequest
{
public string TextContent { get; set; }
public string OutputFileNameNoExt { get; set; }
public string AudioFormat { get; set; }
public string Voice { get; set; }
public double Speed { get; set; }
}
}
The program.cs file:
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using TextToAudioClient;
using TextToAudioClient.Services;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");
builder.Services.Configure<ApiSettings>(builder.Configuration.GetSection("ApiSettings"));
builder.Services.AddScoped(sp =>
{
var apiSettings = sp.GetRequiredService<IOptions<ApiSettings>>().Value;
return new HttpClient { BaseAddress = new Uri(apiSettings.BaseAddress) };
});
builder.Services.AddScoped<TextToAudioService>();
await builder.Build().RunAsync();
The home.razor page (current incarnation):
@page "/"
@using TextToAudioClient.Services
@inject TextToAudioService TextToAudioService
<h3>Text to Audio Converter</h3>
<div class="mb-3">
<label for="textContent" class="form-label">Text Content</label>
<textarea id="textContent" class="form-control" @bind="textContent"></textarea>
</div>
<div class="mb-3">
<label for="outputFileNameNoExt" class="form-label">Output File Name (No Extension)</label>
<input type="text" id="outputFileNameNoExt" class="form-control" @bind="outputFileNameNoExt" />
</div>
<div class="mb-3">
<label for="audioFormat" class="form-label">Audio Format</label>
<select id="audioFormat" class="form-select" @bind="audioFormat">
<option value="mp3">MP3</option>
<option value="opus">Opus</option>
<option value="aac">AAC</option>
<option value="flac">FLAC</option>
</select>
</div>
<div class="mb-3">
<label for="voice" class="form-label">Voice</label>
<select id="voice" class="form-select" @bind="voice">
<option value="alloy">Alloy</option>
<option value="echo">Echo</option>
<option value="fable">Fable</option>
<option value="onyx">Onyx</option>
<option value="nova">Nova</option>
<option value="shimmer">Shimmer</option>
</select>
</div>
<div class="mb-3">
<label for="speed" class="form-label">Speed</label>
<input type="number" id="speed" class="form-control" @bind="speed" min="0.1" max="4.0" step="0.1" />
</div>
<button class="btn btn-primary" @onclick="ConvertTextToAudio">Convert</button>
@if (!string.IsNullOrEmpty(audioUrl))
{
<div class="mt-3">
<h5>Audio URL:</h5>
<a href="@audioUrl" target="_blank">@audioUrl</a>
</div>
}
@code {
private string textContent;
private string outputFileNameNoExt;
private string audioFormat = "mp3";
private string voice = "echo";
private double speed = 0.9;
private string audioUrl;
private async Task ConvertTextToAudio()
{
try
{
audioUrl = await TextToAudioService.ConvertTextToAudioAsync(textContent, outputFileNameNoExt, audioFormat, voice, speed);
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
Not relevant to the problem, but the api root is in the appsettings.json file:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ApiSettings": {
"BaseAddress": "https://texttoaudio.ibtx.local/"
}
}
There’s got to be a bug in my code somewhere, or some setting i missed, but I can’t find it.
Postman has no problems with it: identical params, data, endpoint, and http verb, go figure.