Reputation: 2423
I have a good, working, Web API that works fine from Postman and 2 other dev type clients, however, I cannot get it to take data from a Blazor WASM client (.NET 8).
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.
I ran some more tests and even created another test client in Winforms (super simple) to eliminate the possibility that Blazor is the culprit, however, that was also a no go: same error! The API has a multipart form and it looks like that both Swagger and PostMan correctly format a POST message to support a multipart form (my example doesn't have a file uploader ... yet, until I work out what the problem is, but it will, so multipart forms absolutely has to work!).
I'll attempt to force the httpClient to work with a multipart form, since it doesn't appear to work with default settings. I'm guessing the request header is where the problem lies. (never had problems with webapis before, but this is the first time I've used a multipart form setup, so some secret sauce is needed)
Here is the winforms client code (if I get this to work here, I can replicate on the Blazor end):
using System.Text.Json;
using System.Text;
namespace TextToAudioClient;
public partial class Form1 : Form
{
private readonly HttpClient _httpClient;
public Form1()
{
InitializeComponent();
_httpClient = new HttpClient();
}
private async void btnSendToAPI_Click(object sender, EventArgs e)
{
string requestUri = txtAPIroot.Text.Trim() + txtAPIendpointPath.Text.Trim();
var data = new
{
textContent = txtTextContent.Text.Trim(),
outputFileNameNoExt = txtOutputFileNameNoExt.Text.Trim(),
audioFormat = txtAudioFormat.Text.Trim(),
voice = txtVoice.Text.Trim(),
speed = txtSpeed.Text.Trim()
};
var jsonContent = JsonSerializer.Serialize(data);
var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
try
{
var response = await _httpClient.PostAsync(requestUri, content);
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
MessageBox.Show("Response received: " + responseBody, "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (HttpRequestException httpRequestException)
{
MessageBox.Show("HTTP Request Error: " + httpRequestException.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (Exception ex)
{
MessageBox.Show("An error occurred: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
Upvotes: 1
Views: 447
Reputation: 2423
Turns out the problem was that my client code was not working with multipart form data, so I made the following changes to the ConvertTextToAudioAsync method in the TextToAudioService.cs file. (I can probably remove the json options as case-sensitivity was not the problem)
using System;
using System.Net.Http;
using System.Net.Http.Json;
using System.Net.Mime;
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 data = new
{
textContent = textContent ,
outputFileNameNoExt =outputFileNameNoExt,
audioFormat = audioFormat,
voice = voice,
speed = speed.ToString(),
};
var formData = new MultipartFormDataContent();
formData.Add(new StringContent(data.textContent), "textContent");
formData.Add(new StringContent(data.outputFileNameNoExt), "outputFileNameNoExt");
formData.Add(new StringContent(data.audioFormat), "audioFormat");
formData.Add(new StringContent(data.voice), "voice");
formData.Add(new StringContent(data.speed), "speed");
var response = await _httpClient.PostAsync("api/v1/texttoaudio/convertfrombody", formData);
response.EnsureSuccessStatusCode();
var audioUrl = await response.Content.ReadAsStringAsync();
return audioUrl;
}
catch (HttpRequestException httpRequestException)
{
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);
}
}
}
}
I hope this helps others and was certainly a learning experience (my first file-uploading api).
Upvotes: 0