ASP.NET CORE 2 System.Net.Sockets.SocketException:每当上传文件时

时间:2019-06-20 08:57:05

标签: c# asp.net .net iis asp.net-core

当我尝试通过IIS /服务器上载文件时,总是收到以下错误消息,它在本地工作,但是在服务器上,总是有此问题。

有人知道可能是什么问题吗?

错误消息:

  

调用事件处理程序失败:   Microsoft.AspNetCore.Connections.ConnectionResetException:现有   连接被远程主机强行关闭--->   System.Net.Sockets.SocketException:现有连接   被远程主机强行关闭   Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets.Internal.SocketAwaitable.GetResult()   在   Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets.Internal.SocketConnection.ProcessReceives()   在   Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets.Internal.SocketConnection.DoReceive()   -内部异常堆栈跟踪的结尾--在System.IO.Pipelines.PipeCompletion.ThrowLatchedException()   System.IO.Pipelines.Pipe.GetReadResult(ReadResult&result)位于   System.IO.Pipelines.Pipe.GetReadAsyncResult()位于   System.IO.Pipelines.Pipe.DefaultPipeReader.GetResult(Int16令牌)
  在   Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Http1MessageBody.PumpAsync()   在System.IO.Pipelines.PipeCompletion.ThrowLatchedException()处   System.IO.Pipelines.Pipe.GetReadResult(ReadResult&result)位于   System.IO.Pipelines.Pipe.ReadAsync(CancellationToken令牌)位于   System.IO.Pipelines.Pipe.DefaultPipeReader.ReadAsync(CancellationToken   cancelToken)   Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.MessageBody.ReadAsync(Memory 1 buffer, CancellationToken cancellationToken) at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpRequestStream.ReadAsyncInternal(Memory 1   缓冲区,在   Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpRequestStream.Read(Byte []   缓冲区,Int32偏移量,Int32计数)   Microsoft.AspNetCore.WebUtilities.FileBufferingReadStream.Read(Byte []   缓冲区,Int32偏移量,Int32计数)   System.IO.StreamReader.ReadBuffer()在   System.IO.StreamReader.ReadToEnd()在   Sentry.Extensibility.DefaultRequestPayloadExtractor.DoExtractPayLoad(IHttpRequest   要求)   Sentry.Extensibility.BaseRequestPayloadExtractor.ExtractPayload(IHttpRequest   要求)   Sentry.Extensibility.RequestBodyExtractionDispatcher.ExtractPayload(IHttpRequest   请求)在Sentry.AspNetCore.ScopeExtensions.SetBody(BaseScope   作用域,HttpContext上下文,SentryAspNetCoreOptions选项)位于   Sentry.AspNetCore.ScopeExtensions.Populate(Scope scope,HttpContext   上下文中的SentryAspNetCoreOptions选项)   Sentry.AspNetCore.SentryMiddleware.PopulateScope(HttpContext上下文,   范围范围)在Sentry.Scope.Evaluate()

隐藏代码

try
{
    string folder = "FileLocation/";
    string folderpath = "";

    if (model.Filess != null)
    {
        string fileExtension = Path.GetExtension(model.Filess.FileName);
        fileExtension = fileExtension.ToLower();

        long fileSize = model.Filess.Length;

        if (fileSize <= 10485760)
        {
            folderpath = Path.Combine(__hostingEnvironment.WebRootPath, "Uploads", folder);
            if (!Directory.Exists(folderpath))
            {
                Directory.CreateDirectory(folderpath);
            }

            var parsedContentDisposition =
                ContentDispositionHeaderValue.Parse(model.Filess.ContentDisposition);

            var filename = Path.Combine(__hostingEnvironment.WebRootPath,
                "Uploads", folder, parsedContentDisposition.FileName.Trim('"'));

            using (var stream = System.IO.File.OpenWrite(filename))
            {
                await model.Filess.CopyToAsync(stream);
            }
        }
    };
}
catch (Exception ex)
{

}

1 个答案:

答案 0 :(得分:0)

根据此github issue,MSFT已在asp.net core 2.1上修复了此问题。我建议您可以尝试将服务器上的asp.net核心运行时版本(更新为2.2)。

我还在自己身边创建了一个测试演示并将其发布到IIS服务器,效果很好。

有关我的测试演示的更多详细信息,您可以参考以下代码:

MVC视图:

@model  UploadViewModel
@{
    ViewData["Title"] = "Index";
}

<h1>Index</h1>


<form asp-action="CreateAsync" enctype="multipart/form-data">
    <input asp-for="Id" /> 
    <input asp-for="Filess" />
    <input type="submit" />
</form>

控制器:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using MVCCoreUpload.Models;

namespace MVCCoreUpload.Controllers
{
    public class FileUploadController : Controller
    {

        private readonly IHostingEnvironment _hostingEnvironment;

        public FileUploadController(IHostingEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }

        public IActionResult Index()
        {
            return View(new UploadViewModel());
        }

        public async Task<IActionResult> CreateAsync(UploadViewModel model)
        {
            try
            {
                string folder = "FileLocation/";
                string folderpath = "";

                if (model.Filess != null)
                {
                    string fileExtension = Path.GetExtension(model.Filess.FileName);
                    fileExtension = fileExtension.ToLower();

                    long fileSize = model.Filess.Length;

                    if (fileSize <= 10485760)
                    {
                        folderpath = Path.Combine(_hostingEnvironment.WebRootPath, "Uploads", folder);
                        if (!Directory.Exists(folderpath))
                        {
                            Directory.CreateDirectory(folderpath);
                        }

                        var parsedContentDisposition =
                            ContentDispositionHeaderValue.Parse(model.Filess.ContentDisposition);

                        var filename = Path.Combine(_hostingEnvironment.WebRootPath,
                            "Uploads", folder, parsedContentDisposition.FileName.Trim('"'));

                        using (var stream = System.IO.File.OpenWrite(filename))
                        {
                            await model.Filess.CopyToAsync(stream);
                        }
                    }
                };
            }
            catch (Exception ex)
            {

            }
            return View("index");
        }
    }
}