1

When I pass a username as a value to the ASP.NET Core MVC action method, its parameter gets null as an argument. what can I do to avoid this?

I know it's a common question but I am stuck.

Angular code:

callExternalProject(username : string): Observable<any> {
      
    return this.http.post<any>(`${environment.CMRDashboardURL}/Account/LoginUser`,username) .pipe(
          catchError(error => {
              return throwError(() => new Error(error))
          })     
    );
}

ASP.NET Core MVC code:

[HttpPost]
public IActionResult LoginUser(string  Username)
{
    string viewName = "Login";

    if (string.IsNullOrEmpty(Username))
    {
        ViewBag.Emptybox = "User name can not be empty.";
        return View(viewName, Username);
    }
}

Screenshots:

Frontend screenshot

enter image description here

Backend screenshot

enter image description here

Login the third application from Angular frontend by passing the username from the Angular side

James Z
  • 12,209
  • 10
  • 24
  • 44

1 Answers1

0

WAY 1

I found a official doc why the issue happens.

enter image description here

Custom formatters in ASP.NET Core Web API

If you want to implement this, you can check this answer.


WAY 2

Change your code like below, you will get the value.

this.http
  .post<any[]>(this.apiUrl, null, {
    params: new HttpParams().set('Username', 'jason'),
  })
  .subscribe((data) => {
    this.users = data;
  });

Let me explain to you, from your code, you are using this.http.post<any>(${environment.CMRDashboardURL}/Account/LoginUser,username), the usename send to backend in request body, not params.


Test Result

Yours

I found payload data has string.

enter image description here

Mine

enter image description here

Jason Pan
  • 15,263
  • 1
  • 14
  • 29