Skip to content

Conversion fails #15

Description

@shahankur32

#This conversion is not working code in .Net Core 6

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
using System.IO;
using System.Threading.Tasks;

namespace LargeFilesSample.Controllers
{
    /// <summary>
    /// controller for upload large file
    /// </summary>
    [ApiController]
    [Route("[controller]")]
    public class FileUploadController : ControllerBase
    {
        private readonly ILogger<FileUploadController> _logger;

        public FileUploadController(ILogger<FileUploadController> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// Action for upload large file
        /// </summary>
        /// <remarks>
        /// Request to this action will not trigger any model binding or model validation,
        /// because this is a no-argument action
        /// </remarks>
        /// <returns></returns>
        [HttpPost]
        [Route(nameof(UploadLargeFile))]
        public async Task<IActionResult> UploadLargeFile()
        {
            var request = HttpContext.Request;

            // validation of Content-Type
            // 1. first, it must be a form-data request
            // 2. a boundary should be found in the Content-Type
            if (!request.HasFormContentType ||
                !MediaTypeHeaderValue.TryParse(request.ContentType, out var mediaTypeHeader) ||
                string.IsNullOrEmpty(mediaTypeHeader.Boundary.Value))
            {
                return new UnsupportedMediaTypeResult();
            }

            var reader = new MultipartReader(mediaTypeHeader.Boundary.Value, request.Body);
            var section = await reader.ReadNextSectionAsync();

            // This sample try to get the first file from request and save it
            // Make changes according to your needs in actual use
            while (section != null)
            {
                var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition,
                    out var contentDisposition);

                if (hasContentDispositionHeader && contentDisposition.DispositionType.Equals("form-data") &&
                    !string.IsNullOrEmpty(contentDisposition.FileName.Value))
                {
                    // Don't trust any file name, file extension, and file data from the request unless you trust them completely
                    // Otherwise, it is very likely to cause problems such as virus uploading, disk filling, etc
                    // In short, it is necessary to restrict and verify the upload
                    // Here, we just use the temporary folder and a random file name

                    // Get the temporary folder, and combine a random file name with it
                    var fileName = Path.GetRandomFileName();
                    var saveToPath = Path.Combine(Path.GetTempPath(), fileName);

                    using (var targetStream = System.IO.File.Create(saveToPath))
                    {
                        await section.Body.CopyToAsync(targetStream);
                    }

                    return Ok();
                }

                section = await reader.ReadNextSectionAsync();
            }

            // If the code runs to this location, it means that no files have been saved
            return BadRequest("No files data in the request.");
        }
    }
}

##Converting like below

open Microsoft.IdentityModel.Tokens

open Microsoft.Extensions.Logging

open Microsoft.Extensions.Configuration

open Microsoft.AspNetCore.Http
open Microsoft.AspNetCore.Mvc
open Microsoft.AspNetCore.WebUtilities
open Microsoft.Extensions.Logging
open Microsoft.Net.Http.Headers
open System.IO
open System.Threading.Tasks

[<ApiController>]
[<Route("[controller]")>]
type FileUploadController(configuration : IConfiguration, logger : ILogger<UserAccountController>,
    tokenValidationParams: TokenValidationParameters) as self =
    inherit SootchyControllerBase(configuration, logger)

    [<HttpPost>]
    [<HttpPost("Upload")>]
    member this.UploadLargeFile() = 
        let mutable request = HttpContext.Request
        if not request.HasFormContentType || not (MediaTypeHeaderValue.TryParse (request.ContentType, (* ERROR UnknownNode "DeclarationExpressionSyntax" var mediaTypeHeader *))) || string.IsNullOrEmpty (mediaTypeHeader.Boundary.Value)
        then return new UnsupportedMediaTypeResult()
        let mutable reader = new MultipartReader(mediaTypeHeader.Boundary.Value, request.Body)
        let mutable section = (* ERROR UnknownNode "AwaitExpressionSyntax" await reader.ReadNextSectionAsync() *)
        while (section <> Unchecked.defaultof<_>) do
            let mutable hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse (section.ContentDisposition, (* ERROR UnknownNode "DeclarationExpressionSyntax" var contentDisposition *))
            if hasContentDispositionHeader && contentDisposition.DispositionType.Equals ("form-data") && not (string.IsNullOrEmpty (contentDisposition.FileName.Value))
            then 
                let mutable fileName = Path.GetRandomFileName ()
                let mutable saveToPath = Path.Combine ((Path.GetTempPath ()), fileName)
                let __ = 
                    use targetStream = System.IO.File.Create (saveToPath)
                    (* ERROR UnknownNode "AwaitExpressionSyntax" await section.Body.CopyToAsync(targetStream) *)
                return (Ok ())
            section <- (* ERROR UnknownNode "AwaitExpressionSyntax" await reader.ReadNextSectionAsync() *)
        BadRequest ("No files data in the request.")

image

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions