Angular2在C#中发布请求参数处理

时间:2017-02-06 13:00:13

标签: c# angular asp.net-web-api

Angular 2 Code 请求URl:http://loacalhost:8800/MyController/SaveBookings

let data = {
    occupationListStr: occupations,
    rOccupationListStr: roccsStr,
};
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
this.http.post('MyController/SaveBookings', JSON.stringify(data),options)
    .then(res => {  
        return res.json()
    })
    .catch(this.handleError);

C#代码

控制器

问题: Request.QueryString值OccupListStr和rOccupationListStr为空

public ActionResult SaveBookings()
{
    dynamic occupationListStr = Request.QueryString["occupationListStr"];
    dynamic rOccupationListStr = Request.QueryString["rOccupationListStr"];

    <....Do something.....>

    return <return something>;
}

2 个答案:

答案 0 :(得分:1)

  1. 你不需要字符串化
  2. 使用OccupListStr,rOccupationListStr属性在后端创建一个类(比如[httpPost] public IHttpActionResult Post([FromBody]Occupation objOccupation) { }
  3. 从课程中您可以使用脚手架自动创建控制器。如果你不想要
  4. $test

答案 1 :(得分:1)

在您的问题中,您在请求正文中以Json(使用JSON.stringify(data))发送数据,但在您的操作中,您希望查询字符串中包含数据。

您应该将动作中的Json解析为某个模型:

// you can use your own model (some class to parse Json to) instead of "dynamic"
[HttpPost]
public ActionResult SaveBookings([FromBody]dynamic data) 
{
    var occupationListStr = data.occupationListStr;
    var rOccupationListStr = data.rOccupationListStr;

    <....Do something.....>

    return <return something>;
}

您应该在Angular 2中更改您的请求:

this.http.post('MyController/SaveBookings?occupationListStr=' + occupations + '&rOccupationListStr=' + roccsStr, null, options)
    .then(res => {  
        return res.json()
    })
    .catch(this.handleError);