【问题标题】:Not sending data to server in Angular 6 and ASP.NET Core在 Angular 6 和 ASP.NET Core 中不向服务器发送数据
【发布时间】:2019-05-04 02:34:19
【问题描述】:

我使用 ASP.NET Core 创建了一个服务器,前端使用 Angular 6。

我在Angular 6中创建了一个表单。在组件中,我创建了一个向服务层发送数据并将数据发送到服务器的函数,但它没有进入服务器。它没有显示任何错误。

有什么问题?是后端还是前端?

用户.ts

changeActive(id:number) {
    this.userService.GetUserById(id).subscribe((data) => {
        if(data.isActive)
        {
            data.isActive = false;
        } else {  
            data.isActive = true;
        }

        console.log("send data in service");
        this.userService.Active(data);
    })
}

角度服务:

public Active(user:IUser):Observable<IUser> {
    console.log("we get data from component");
    console.log(user);
    return this.http.post<IUser>(this.baseUrl + 'Active', user, { headers: this.headers })
               .pipe(tap((user: IUser) => this.log(`Active user w/ email=${user}`)),
                     catchError(this.handleError<IUser>('Active user'))
          );
}

ASP.NET Core 控制器:

[HttpPut("Active")]
public async Task<ActionResult> ActiveAccount(User model)
{
        if (ModelState.IsValid)
        {
            var user = await _applicationUserManager.FindUserById(model.Id);
            user.IsActive = model.IsActive;
            await _applicationUserManager.UpdateAsync(user);
            return Ok();
        }

        return BadRequest();
}

【问题讨论】:

  • 尝试在 API 的 ActiveAccount 属性中将 HttpPut 更改为 HttpPost。要么那个,要么做一个put而不是一个post。
  • 你没有订阅从Active返回的 Observable
  • @R.Richards 我尝试了,但它不起作用
  • 进行@user184994 建议的更改后会发生什么?我希望您现在收到一条错误消息,因此请包含它。
  • 它不会显示任何错误或消息

标签: angular asp.net-core angular6 asp.net-core-webapi angular-http


【解决方案1】:

针对您的问题一一检查以下几点:

  1. 致电subscribe 处理Active

    this.userService.Active(data).subscribe(result => {
      console.log(result);
    });
    
  2. 不确定this.baseUrl 的值是多少,它应该指向控制器地址。如果你的控制器是这样的,你需要将api/sampledata附加到你的基本url,或者如果你的基本url是http://localhost:port,你需要将'Active'更改为api/SampleData/Active

    [Route("api/[controller]")]
    public class SampleDataController : Controller
    
  3. 不确定您的标头是什么,通常,您将请求传递为application/json,通过添加FromBody 更改如下操作。

    [HttpPost("Active")]
    public async Task<ActionResult> ActiveAccount([FromBody]User model)
    {
        //your code.
    }
    
  4. 注意HttpPost,如果你从角度调用this.http.post&lt;IUser&gt;,你需要在控制器动作中使用HttpPost

  5. 还有一点,在网络浏览器中按F12 来调试您的客户端代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-03
    • 2015-03-11
    • 1970-01-01
    相关资源
    最近更新 更多