【问题标题】:How to pass integer value to Controller from httppost method in angular 4?如何在角度 4 中从 httppost 方法将整数值传递给控制器​​?
【发布时间】:2018-01-15 19:40:13
【问题描述】:

在我们的 Angular4 MVC 应用程序中,我们使用 http 服务从数据层获取数据。 请看代码sn-p

this.http.post(_this.baseUrl + "api/User/" + user.UserId)

在 API 控制器中,我没有得到 UserId 值。

如果我传递一个字符串值,那么没有问题。

请任何人帮忙解决这个问题。

【问题讨论】:

  • 能否请您发布整个控制器以及服务?

标签: angular asp.net-web-api


【解决方案1】:

根据您使用的 URL,要进行后调用,您只需创建如下控制器操作:-

[HttpPost]
public IActionResult Post([FromRoute]int userId)
{
    var id = userId;
    return Ok();
}

如果用户 id 是字符串,那么

[HttpPost]
public IActionResult Post([FromRoute]string userId)
{
    var id = userId;
    return Ok();
}

【讨论】:

  • 这里我将 userId 设为 0。有什么建议吗?
  • 用户id的值是多少?是整数还是字符串?如果它是 int 它应该可以工作,如果它是 string 然后将 int 类型更改为 string。我已经更新了答案
【解决方案2】:

试试这个

this.http.post(_this.baseUrl + "api/User/MethodName?userId=1");

控制器

[HttpGet]
public string MethodName(long userId)
{
     //do you operation
}

请通过安装Postman 或类似客户端检查网址是否正确

【讨论】:

    【解决方案3】:

    比方说,你得到了这样的东西:

    @POST
    @Path("/deleteFile/{userId}/{fileName}")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public boolean deleteFile(@PathParam("userId") Integer userId, @PathParam("fileName") String fileName);
    

    那么Service函数应该是这样的:

    public deleteFile( userId: number, fileName: string ): Observable<boolean> {
        const headers = new Headers( { 'Content-Type': 'application/json' } );
        /* The option withCredentials: true is used for the CORS variant, that is, when our REST server is on a different WEB server than our node.js server, where my Angular2 development application is.
         */
        const options = new RequestOptions( { headers: headers, withCredentials: true } );
    
        return this.http.post( this.url + '/deleteFile/' + userId + '/' + fileName, null, options )
            .map( this.extractData )
            .catch( this.handleError );
    }
    

    这是我不久前用于我的应用程序的代码的一个简单示例,它应该可以工作。

    【讨论】:

      猜你喜欢
      • 2020-05-19
      • 1970-01-01
      • 1970-01-01
      • 2018-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-04
      • 2016-12-19
      相关资源
      最近更新 更多