gpt4 book ai didi

c# - 如何从 web api 中的 Angular 帖子读取文件?

转载 作者:行者123 更新时间:2023-11-30 15:23:26 29 4
gpt4 key购买 nike

我成功实现了基于 OWIN 的 token 身份验证。

但是在实现这个之前,当我尝试使用 HttpContext.Current.Request.Files[i].FileName 从我的 Angular 应用程序获取发布的文件多部分表单数据到 web api 时,它很容易给我发布我想要的文件。

但是在实现基于 owin 的 token 身份验证后,我无法获取发布的文件并且在同一行发生错误。

通过在这个错误上花费更多的时间,我已经从互联网上找到了大部分答案,但我仍然无法解决我的问题。

大多数提供的解决方案都说您无法在自托管容器中访问 HttpContext.Current.Request

app.UseWebApi(config);

我真的卡在这上面了,所以请帮助我。

错误是:

The line 306 is : HttpContext.Current.Request.Files[i].FileName

An error has occurred.
ExceptionMessage: This method or property is not supported after HttpRequest.GetBufferlessInputStream has been invoked.
ExceptionType: System.Web.HttpException
StackTrace
at System.Web.HttpRequest.EnsureFiles()
at System.Web.HttpRequest.get_Files()
at Nullplex.Rest.Controllers.UserBasicController.UpdateUserBasicByID(UserBasic UserBasic) in d:\BitBucket\PayBackRestApp \Nullplex.Rest\Controllers\UserBasicController.cs:line 306
at lambda_method(Closure , Object , Object[] )
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.c__DisplayClass10 .b__9(Object instance, Object[] methodParameters)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor .ActionExecutor.Execute(Object instance, Object[] arguments)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor .ExecuteAsync(HttpControllerContext controllerContext, IDictionary2 arguments, CancellationToken cancellationToken )

End of stack trace from previous location where exception was thrown

at System.Runtime .CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices .TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices .TaskAwaiter1.GetResult()
at System.Web.Http.Controllers.ApiControllerActionInvoker.d__0.MoveNext()

End of stack trace from previous location where exception was thrown

at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime .CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime .CompilerServices.TaskAwaiter1.GetResult()
at System.Web.Http.Controllers.ActionFilterResult. d__2.MoveNext()

最佳答案

我像这样在 web api 中读取从 Angular 发布的文件

if (!this.Request.Content.IsMimeMultipartContent("form-data"))
{
var provider = new MultipartMemoryStreamProvider();
await this.Request.Content.ReadAsMultipartAsync(provider);

var content = provider.Contents.First();
var buffer = await content.ReadAsByteArrayAsync();

现在缓冲区包含文件数据为 byte[]

关于c# - 如何从 web api 中的 Angular 帖子读取文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34461985/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com