I have an angular 12 UI that is communicating with a .net 6 API. When a parameter in a query string is null or undefined the API is interpreting it as a string value of "null" or "undefined". Relevant code below
angular code:
getDummyUser(type: string, testId: string):
Observable<UserDto> {
var url = `api/users/get-dummy-user?type=${encodeURIComponent(type)}&testId=${encodeURIComponent(testId)}`;
return this.httpClient.get<any>(url)
.pipe(
finalize(() =>
this.hideLoadingIndicators()
),
catchError(err => {
return throwError(err);
})
);
}
.net 6 api parameter signature
[HttpGet]
[Route("get-dummy-user")]
public async Task<IActionResult> GetDummyUser
(
string type,
string testId
)
I have tried using the [FromQuery] attribute but the result is the same. I also cannot send '' from the angular app as the API will then throw a 400 error (bad request). Has anyone had any experience in this? Thanks in advance
CodePudding user response:
I don't know if this is something to do with new .net 6 or angular 12 but it appears that nowadays you have to send an empty string as the parameter AND make string nullable on the .net side. I'm not sure why string has to be declared as nullable now when it is... inherently nullable. Having issues with code formatting, apologies. Working solution below
getDummyUser(type) {
this.userProvider.getDummyUser(type, '').subscribe(u => {
});
getDummyUser(type: string, testId: string):Observable<UserDto> {var url = `api/users/get-dummy-usertype=${encodeURIComponent(type)}&testId=${encodeURIComponent(testId)}`;return this.httpClient.get<any>(url).pipe(
finalize(() =>
this.hideLoadingIndicators()
),
catchError(err => {
return throwError(err);
})
);
[HttpGet]
[Route("get-dummy-user")]
public async Task<IActionResult> GetDummyUser
(
[FromQuery] string type,
[FromQuery] string? testId
)
