Api丢失丢失的参数

本文关键字:参数 Api | 更新日期: 2023-09-27 18:13:09

嗨,我有这段代码来运行我的api方法

export class MessageService {
    constructor(private http: Http) {
    }
    addMessage(textToSend: string) {
        return this.http.post("/api/SendMessage", textToSend); //<- Everytime i have some text in textToSend and this is ok 
    }
}

之后在我的Api中我的参数是等于null

[HttpPost]
[Route("/api/SendMessage")]
public void SendMessage(string msg) //null value
{
    //some code
}

Api丢失丢失的参数

你的控制器动作正在接受一个查询参数,而不是路由器参数或模型。

如果要接受某个路由参数,需要将其添加到路由中。

如果你想在主体中传递一个模型或值,你必须用[FromBody]属性标记参数。

[HttpPost]
[Route("/api/SendMessage")]
public void SendMessage([FromBody]string msg)
{
    MessageBox MsgBox = new MessageBox();
    MsgBox.AddMsgToMsgBox(msg);
}

如果你没有定义任何东西,控制器期望参数作为查询/api/SendMessage?msg=someMessage传递(你不应该在REST服务中这样做,因为它不是很"RESTful"

可能的解决方案1:

addMessage(textToSend: string) {
    let body = JSON.stringify({ textToSend });
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    return this.http.post("/api/SendMessage/", body, options);
}
// Server side -1
[HttpPost]
[Route("/api/SendMessage")]
public void SendMessage([FromBody]IDictionary<string, string> msg)
{
    var textToSend = msg["textToSend"];
}
// Or create a model and use it
//Server side -2
public class Model
{
    public string textToSend { get; set; }
}
public void SendMessage([FromBody]Model model)

可能解决方案2:

addMessage(textToSend: string) {
    return this.http.post("/api/SendMessage/" + textToSend);
}
[HttpPost]
[Route("/api/SendMessage/textToSend")]
public void SendMessage(string textToSend)
{
    //some code
}

try

 addMessage(textToSend: string) {
    return this.http.post("/api/SendMessage", msg); //<- Everytime i have some text in textToSend and this is ok 
}

将变量的名称更改为与控制器

中期望的名称匹配。