C#ASP.NET核心web api httprequestmessage重写 [英] C# ASP.NET core web api httprequestmessage rewrite
问题描述
我正在从ASP.NET Web API重写一个POST方法到ASP.NET Core我不知道如何重写下面的代码。此代码在ASP.NET Web API中工作正常。
ASP.NET Web Api:
I am re-writing a POST method from ASP.NET Web API to ASP.NET Core I am not sure how to re-write the below code. This code works fine in ASP.NET Web API.
ASP.NET Web Api:
public IHttpActionResult Post()
{
var rawds = ConvertByteToArray(Request.Content.ReadAsStreamAsync().Result); //error here at Content
//do something
}
private byte[] ConvertByteToArray(Stream stream)
{
using (MemoryStream ms = new MemoryStream())
{
stream.CopyTo(ms);
return ms.ToArray();
}
}
我的尝试:
当我在ASP.NET Core中编写如下相同的代码时,我得到以下错误'HttpRequest'不包含'Content'的定义,也没有扩展方法'Content'接受a可以找到类型'HttpRequest'的第一个参数(你是否缺少using指令或程序集引用?)
ASP.NET核心:
What I have tried:
When I write the same code as below in ASP.NET Core I get the following error 'HttpRequest' does not contain a definition for 'Content' and no extension method 'Content' accepting a first argument of type 'HttpRequest' could be found (are you missing a using directive or an assembly reference?)
ASP.NET Core:
public IActionResult Post()
{
var rawds = ConvertByteToArrayAsync(Request.Content.ReadAsStreamAsync().Result);
//do something
}
public static async Task<byte[]> ConvertByteToArrayAsync(Stream stream)
{
using (var ms = new MemoryStream(2048))
{
await request.Body.CopyToAsync(ms); //get error here at request
return ms.ToArray();
}
}
推荐答案
await request.Body.CopyToAsync(ms);
1.无论如何,它应该是Request(R而不是r)!
2.似乎是一个逻辑错误,你将'Result'流传递给函数但不使用它?你可能想把它复制到ms?
1. In any case it should be Request (R and not r)!
2. It seems to be a logic error, that you pass the 'Result' stream to the function but do not use it? You probably meant to copy it to ms?
这篇关于C#ASP.NET核心web api httprequestmessage重写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!