c# - ASP.NET Core 中的 HttpRequestMessage 是什么?

标签 c# json rest asp.net-core asp.net-core-webapi

我找到了一个 blog post这显示了如何将 POSTed JSON 作为字符串接收。

我想知道在 Controller 的 REST Post 方法中执行与以下代码相同的事情的新 native 方法是什么:

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

    // Do something with the string 

    return new HttpResponseMessage(HttpStatusCode.Created);
}

下面的另一个选项对我不起作用,我想是因为我没有在请求 header 中使用 Content-Type: application/json(无法更改),我得到一个 415。

public HttpResponseMessage Post([FromBody]JToken jsonbody)
{
    // Process the jsonbody 

    return new HttpResponseMessage(HttpStatusCode.Created);
}

最佳答案

在 .Net Core 中,他们合并了 Web API 和 MVC,所以你可以像这样用 IActionResult 来做或其衍生物之一。

public IActionResult Post([FromBody]JToken jsonbody)
{
    // Process the jsonbody 

    return Created("", null);// pass the url and the object if you want to return them back or you could just leave the url empty and pass a null object
}

关于c# - ASP.NET Core 中的 HttpRequestMessage 是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45568380/

相关文章:

c# - ASP.NET 表单例份验证默认重定向 [工作] 和重定向到带查询字符串的请求页面 [不工作]

c# - 如何使用 dotnetbrowser 获取 ajax 请求响应正文?

asp.net-mvc - ASP.NET MVC 读取原始 JSON 发布数据

json - 将 JSON 字段转换为 ReasonML 变体

rest - 如果资源正在使用且无法删除,请更正 Delete API 的 HTTP 响应代码

http - REST、HTTP DELETE 和参数

angularjs - REST 乐观锁定和多个 PUT

c# - 使用 C# Interop.Excel 从 NamesManager 中删除重复名称

c# - 使用 C# 允许在 XML 序列化中重复节点名称

php - 为dataTable jquery插件获取数组时出现"Illegal string offset"错误