简体   繁体   English

httpContext.Request.GetRawBodyStringAsync()与[FromBody]字符串正文相同吗?

[英]is httpContext.Request.GetRawBodyStringAsync() the same as [FromBody] string body?

I am trying to get my head around things (sorry for stupid questions). 我正在努力解决问题(对愚蠢的问题感到抱歉)。 I get a message request from an Apple device client to my wep api and I am wondering how to handle it. 我收到了来自Apple设备客户端到我的wep api的消息请求,我想知道如何处理它。 In .NET Framework, I used to handle the message using: 在.NET Framework中,我曾经使用以下方法处理消息:

 public async Task<HttpResponseMessage> Server(HttpRequestMessage request)
        {
            var message =  await request.Content.ReadAsStringAsync();

This worked fine but moving to .NET Core, request is always empty. 这工作正常,但移至.NET Core,请求始终为空。 Hence I've moved on to doing this (this works below): 因此,我继续进行此操作(以下操作):

[HttpPut]
[Route("server")]
public async Task<IActionResult> DoSomething()
{
    var requestBody = await HttpContext.Request.GetRawBodyStringAsync();
}

But I am wondering if the above is the correct way of handling such requests and I have also see the use of [FromBody] and wondering it's better to use that but it does not work for me. 但是我想知道上面是否是处理此类请求的正确方法,并且我也看到了[FromBody]的使用,并且想知道最好使用它,但它对我不起作用。

[HttpPut]
[Route("server")]
public async Task<IActionResult> DoSomething([FromBody] string requestBody)
{
   //doesn't get called?
}

The parameter name in your action needs to match the property name being sent in the request. 您操作中的参数名称需要与请求中发送的属性名称匹配。

eg if the request is sending: varA=string1&varB=string2&varc=string3 例如,如果请求正在发送: varA=string1&varB=string2&varc=string3

Then your action method should look like this: 然后,您的操作方法应如下所示:

[HttpPut]
[Route("server")]
public async Task<IActionResult> DoSomething([FromBody] string varA,[FromBody] string varB,[FromBody] string varC)
{

}

Alternatively, you can have a model class for these type of requests: 另外,您可以为这些类型的请求提供模型类:

class RequestModel{
public string VarA {get;set;}
public string VarB {get;set;}
public string VarC {get;set;}
}

    [HttpPut]
    [Route("server")]
    public async Task<IActionResult> DoSomething([FromBody] RequestModel request)
    {

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM