从 Angular 前端发送 post 请求后,空参数被传递到 API 控制器

问题描述 投票:0回答:1

我在后台开发了登录功能

[Route("api/")]
[ApiController]
public class LoginController : ControllerBase
{
    private readonly ILoginService _loginService;

    public LoginController(ILoginService loginService)
    {
        _loginService = loginService;
    }

    [HttpPost("login")]
    [AllowAnonymous]
    public async Task<IActionResult> Login([FromBody]UserForRouteDto resource, CancellationToken cancellationToken)
    {
        try
        {
            var response = await _loginService.Login(resource, cancellationToken);
            return Ok(response);
        }
        catch (Exception e)
        {
            return BadRequest(new { ErrorMessage = e.Message });
        }
    }
}

UserForRouteDto类设计为

public class UserForRouteDto
{
    public string? Username { get; set; }
    public string? Password { get; set; }
    public string? Role { get; set; }

    public UserForRouteDto()
    {
            
    }
}

前端是我同事开发的。我没有 Angular 经验,所以我只是将代码粘贴到这里。

import { Injectable } from '@angular/core';
import { User } from '../models/user';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class UserService {
  
  private apiUrl = "https://localhost:7213"
  constructor(
    private http: HttpClient
  ) { }

  getLoginDetails(userDetails:User): Observable<void>{
    return this.http.post<void>(this.apiUrl+'/login',  userDetails);
  }
}

User 类设计为

export interface User {
    Username: string,
    Password: string
    Role: string
}

然后启动后端和前端后,我单击登录按钮,后端被触发。但参数resource为空。

我尝试了很多在网上找到的解决方案,但没有一个适合我。我尝试删除 [FromBody] 属性并将 getLoginDetails 更改为

getLoginDetails(userDetails:User): Observable<string>{
    const headers = { 'content-type': 'application/json'}  
    const body=JSON.stringify(userDetails);
    return this.http.post<string>(this.apiUrl+'login',  body,{'headers':headers});
  }

但我仍然得到空值。 然后我使用 HttpRequestMessage 类更改了后端登录函数中的参数。有趣的是,虽然我得到空内容,但该方法显示 GET 而不是预期的 POST

另一件事困扰我的是,我只能访问 url http://localhost:4200 下的页面。网址http://localhost:4200/loginhttp://localhost:4200/api/login 不起作用。 我在这上面花了很多时间,但仍然没有任何线索。有人可以帮忙吗?

angular asp.net-core-webapi http-post frombodyattribute
1个回答
0
投票

又经过数百次测试,我找到了解决方案。前端的方法应该是

getLoginDetails(userDetails:User): Observable<User>{     
    const headers = { 'content-type': 'application/json'}       
    return this.http.post<User>(this.apiUrl+'/login', userDetails {'headers':headers});   
}

看来使用这种方式后端是可以接收到请求内容的。

© www.soinside.com 2019 - 2024. All rights reserved.