部署更新API时如何解决400错误的错误请求

时间:2019-08-13 11:23:39

标签: c# web asp.net-core

在请求文件上传API时,我收到了400个错误代码,请求错误。

我在asp.net核心中构建了用于文件上传的后端和前端,当我在PC上使用IIS运行它(使用Visual Studio 2017)时,它可以在localhost中运行。 保存和更新API都可以在我的本地环境中使用,但是如果我部署代码,则更新API不能使用

前端代码如下:

 public static async Task<HttpResponseMessage> UploadFile(string uploadUrl, string filePath, FFFileInfo fileInfo)
        {
            string fileName = fileInfo.Name + "." + fileInfo.Extension;
            string contentType = MimeTypes.GetMimeType(filePath);

            using (var hc = new HttpClient())
            {
                hc.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(TokenType, AccessToken);
                hc.DefaultRequestHeaders.Accept.Clear();
                hc.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                Stream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                StreamContent streamContent = CreateFileContent(fileStream, fileName, contentType);
                // StreamContent streamContent = CreateFileContent(fileStream, "image.jpg", "image/jpeg");  // Multiple file upload

                var requestContent = new MultipartFormDataContent("Upload Id" + DateTime.Now.ToString(CultureInfo.InvariantCulture));
                requestContent.Add(streamContent, fileInfo.Name, fileName);
                var progressContent = new ProgressableStreamContent(
                     requestContent,
                     4096,
                     (sent, total) =>
                     {
                         //Console.WriteLine("Uploading {0}/{1}", sent, total);
                         int percentage = (int) Math.Round((double)(100 * sent) / total);
                         Console.Write("\r{0}\t{1}%", fileInfo.Path, percentage);
                         if (sent == total)
                         {
                             Console.WriteLine();
                         }
                     });

                var response = await hc.PostAsync(new Uri(uploadUrl), progressContent);

                return response;
            }
        }

如下所示的后端代码:

[HttpPost]
        [DisableFormValueModelBinding]
        public async Task<IActionResult> UploadFiles([FromQuery] FFFileInfo fileinfo)
        {
            if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
            {
                return BadRequest($"Expected a multipart request, but got {Request.ContentType}");
            }
            authUser = User.ToAuthUser();
            userId = authUser.UserId();
            customerId = authUser.CustomerId();

            Server.Model.File new_file = new Server.Model.File();

            var boundary = MultipartRequestHelper.GetBoundary(MediaTypeHeaderValue.Parse(Request.ContentType), _defaultFormOptions.MultipartBoundaryLengthLimit);
            var reader = new MultipartReader(boundary, HttpContext.Request.Body);

            var section = await reader.ReadNextSectionAsync();

            MemoryStream writeStream = new MemoryStream();
            byte[] content = null;

            while (section != null)
            {
                ContentDispositionHeaderValue contentDisposition;
                var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out contentDisposition);
                int chunkSize = 1024;
                byte[] byte_file = new byte[chunkSize];
                int bytesRead = 0;

                new_file.File_Content = byte_file;

                if (hasContentDispositionHeader)
                {
                    if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                    {
                        //await section.Body.CopyToAsync(targetStream);
                        using (var byte_reader = new BinaryReader(section.Body))
                        {
                            do
                            {
                                bytesRead = byte_reader.Read(byte_file, 0, byte_file.Length);
                                if(bytesRead <= 0)
                                {
                                    content = writeStream.ToArray();
                                }
                                writeStream.Write(byte_file, 0, bytesRead);
                            } while (bytesRead > 0);

                            content = writeStream.ToArray();

                        }
                    }
                }
                // Drains any remaining section body that has not been consumed and
                // reads the headers for the next section.
                section = await reader.ReadNextSectionAsync();
            }

            try
            {
                new_file = new Server.Model.File
                {
                    File_Name = fileinfo.Name,
                    File_Path = fileinfo.Path,
                    File_Ext = fileinfo.Extension,
                    Check_Sum = fileinfo.Checksum,
                    ToolSerialNumber = fileinfo.ToolSerialNumber,
                    FileSize = fileinfo.Length,
                    File_Content = content,
                    UserId = userId,
                    CustomerId = customerId
                };
            }
            catch (Exception ex)
            {
                return BadRequest(ex);
            }

            try
            {
                if (!fileService.isExist(new_file.File_Path, userId))
                {
                    fileService.SaveFile(new_file);
                }
                else
                {
                    Server.Model.File existing = fileService.GetFileByPath(new_file.File_Path, userId);
                    fileService.UpdateFile(existing, new_file);
                }

                //set file content to null to response with small data
                new_file.File_Content = null;
                return Ok(new_file);
            }
            catch (Exception ex)
            {
                logger.LogError("DB action error {0}", ex.ToString());
                return BadRequest(ex);
            }
        }

您可以看到上面的代码,保存和更新使用的是相同的代码,但只有更新在部署时不起作用。 对我来说很奇怪。

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。 这段代码是由我的客户端部署的,我无法检查他部署的数据库。 根据研究和测试,我想到了一个可能与权限问题相关的想法。 因此,我们检查它的数据库。

最后,我们发现当前用户具有插入,删除,选择权限,但没有更新权限。 授予更新权限后,它可以正常运行