Search code examples
c#asp.net-coreasp.net-core-routing

Why I can't get a post request in the controller?


I want to get the body of a post in a controller.

Here is my code:

[HttpPost]
public string GetMsg([FromBody]GetMsgModel GSM)
{
    return "";
}

And posted class

public class GetMsgModel { 
    public string ToUserName { get; set; }
    public string FromUserName { get; set; }
    public string CreateTime { get; set; }
    public string MsgType { get; set; }
    public string Content { get; set; }
    public string MsgId { get; set; }
}

I added a breakpoint to the GetMsg and send a post via postman with this XML body:

<xml>
  <ToUserName>123</ToUserName>
  <FromUserName>456</FromUserName>
  <CreateTime>1348831860</CreateTime>
  <MsgType>789</MsgType>
  <Content>000</Content>
  <MsgId>1234567890123456</MsgId>
</xml>

enter image description here

Well, the breakpoint does not run at all.

What's wrong with this? There is another HttpGet method in the same controller and it works well. It seems it is not the problem of the controller yet.


Solution

  • If you're using Net Core Add to Statup.cs

    services.AddXmlSerializerFormatters();
    

    And the XML should be

    <GetMsgModel>
      <ToUserName>123</ToUserName>
      <FromUserName>456</FromUserName>
      <CreateTime>1348831860</CreateTime>
      <MsgType>789</MsgType>
      <Content>000</Content>
      <MsgId>1234567890123456</MsgId>
    </GetMsgModel>
    

    Hope it helps