web api Archives - Learn Smart Coding https://blogs.learnsmartcoding.com/tag/web-api/ Everyone can code! Thu, 16 Apr 2020 02:49:09 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.1 209870635 This project references NuGet package(s) that are missing on this computer. https://blogs.learnsmartcoding.com/2020/04/16/this-project-references-nuget-package-that-are-missing-error/ https://blogs.learnsmartcoding.com/2020/04/16/this-project-references-nuget-package-that-are-missing-error/#respond Thu, 16 Apr 2020 02:49:09 +0000 https://karthiktechblog.com/?p=463 Many of us have ran into issue “This project references NuGet package(s) that are missing on this computer”. There are many different reason as to why someone will get this error while you build the solution. Error Details This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download […]

The post This project references NuGet package(s) that are missing on this computer. appeared first on Learn Smart Coding.

]]>
Many of us have ran into issue “This project references NuGet package(s) that are missing on this computer”. There are many different reason as to why someone will get this error while you build the solution.

Error Details

This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is ..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props

Looking at the error, it is triggered from somewhere in the code. Let’s go to the .csproj file and this can be found at the end of the file.

<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
    <PropertyGroup>
      <ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
    </PropertyGroup>
    <Error Condition="!Exists('..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.1\build\net46\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.1\build\net46\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props'))" />
  </Target>

A solution to “This project references NuGet package that are missing error”

The error is tied to the package Microsoft.CodeDom.Providers.DotNetCompilerPlatform. Follow the below three steps to solve the issue.

Step 1

Remove the package from package.config file.

<package id="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" version="2.0.1" targetFramework="net46" />

Step 2

Edit the .csproj project file and removed the below settings

<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
    <PropertyGroup>
      <ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
    </PropertyGroup>
    <Error Condition="!Exists('..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.1\build\net46\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.1\build\net46\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props'))" />
  </Target>

Step 3

Go to package manager console and run the command Update-Package –reinstall

Step # 2 and 3 were given by other users and I appreciate those users. Point # 1, removing the Microsoft.CodeDom.Providers.DotNetCompilerPlatform from package.config file is more important. Also, after running the command mentioned in step #3, the issue resolved. All unwanted packages removed and required package reference updated

Reference

There are other similar fixes which might work for few scenarios. Take a look at this post from StackOverflow

Also Read

How to upload a file in ASP.NET Web API

Conclusion

In this post, I showed how to resolve a common error “This project references NuGet package(s) that are missing on this computer”. That’s all from this post. If you have any questions or just want to chat with me, feel free to leave a comment below.

The post This project references NuGet package(s) that are missing on this computer. appeared first on Learn Smart Coding.

]]>
https://blogs.learnsmartcoding.com/2020/04/16/this-project-references-nuget-package-that-are-missing-error/feed/ 0 463
How to upload a file with .NET CORE Web API 3.1 using IFormFile https://blogs.learnsmartcoding.com/2020/04/04/how-to-upload-a-file-with-net-core-web-api-3-1-using-iformfile/ https://blogs.learnsmartcoding.com/2020/04/04/how-to-upload-a-file-with-net-core-web-api-3-1-using-iformfile/#respond Sat, 04 Apr 2020 15:41:08 +0000 https://karthiktechblog.com/?p=434 In this post, I will show how to upload a file with .NET CORE Web API 3.1 using IFormFile. Uploading a file is a process of uploading a file from the user’s system to a hosted web application server. You may choose to store the file in the web server’s local disc or in the […]

The post How to upload a file with .NET CORE Web API 3.1 using IFormFile appeared first on Learn Smart Coding.

]]>
In this post, I will show how to upload a file with .NET CORE Web API 3.1 using IFormFile.

Uploading a file is a process of uploading a file from the user’s system to a hosted web application server. You may choose to store the file in the web server’s local disc or in the database.

With ASP NET CORE, it is easy to upload a file using IFormFile that comes under the namespace "Microsoft.AspNetCore.Http". IFormFile represents a file sent with the HttpRequest.

Upload File using IFormFile in .NET Core

Methods of uploading files have changed since DOT NET CORE was introduced. To upload a single file using .NET CORE Web API, use IFormFile which Represents a file sent with the HttpRequest.

This is how a controller method looks like which accepts a single file as a parameter.

[HttpPost("upload", Name = "upload")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(typeof(string), StatusCodes.Status400BadRequest)]
        public async Task<IActionResult> UploadFile(
         IFormFile file,
         CancellationToken cancellationToken)
        {
            if (CheckIfExcelFile(file))
            {
                await WriteFile(file);
            }
            else
            {
                return BadRequest(new { message = "Invalid file extension" });
            }

            return Ok();
        }

Code Explanation

The controller action method “UploadFile” accepts file using IFormFile as a parameter. We check whether the file sent is in the required format using a custom private method named “CheckIfExcelFile” which checks whether an incoming file is an excel file. You may change this based on your needs.

       
 private bool CheckIfExcelFile(IFormFile file)
        {
            var extension = "." + file.FileName.Split('.')[file.FileName.Split('.').Length - 1];
            return (extension == ".xlsx" || extension == ".xls"); // Change the extension based on your need
        }

Once the validation is a success, we save the file to the disc using “WriteFile(file)” method.

private async Task<bool> WriteFile(IFormFile file)
        {
            bool isSaveSuccess = false;
            string fileName;
            try
            {
                var extension = "." + file.FileName.Split('.')[file.FileName.Split('.').Length - 1];
                fileName = DateTime.Now.Ticks + extension; //Create a new Name for the file due to security reasons.

                var pathBuilt = Path.Combine(Directory.GetCurrentDirectory(), "Upload\\files");

                if (!Directory.Exists(pathBuilt))
                {
                    Directory.CreateDirectory(pathBuilt);
                }

                var path = Path.Combine(Directory.GetCurrentDirectory(), "Upload\\files",
                   fileName);

                using (var stream = new FileStream(path, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }

                isSaveSuccess = true;
            }
            catch (Exception e)
            {
               //log error
            }

            return isSaveSuccess;
        }

Yes, to upload a file with .NET CORE Web API 3.1 using IFormFile is very easy with DOTNET CORE Web API.

How to upload a file with .NET CORE Web API 3.1 using IFormFile

Here is the short video tutorial.

Upload file from Angular, Video demo

Complete Code

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

namespace KarthikTechBlog.API.Controllers
{
    [HttpPost("upload", Name = "upload")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(typeof(string), StatusCodes.Status400BadRequest)]
        public async Task<IActionResult> UploadFile(
         IFormFile file,
         CancellationToken cancellationToken)
        {
            if (CheckIfExcelFile(file))
            {
                await WriteFile(file);
            }
            else
            {
                return BadRequest(new { message = "Invalid file extension" });
            }

            return Ok();
        }

        /// 
        /// Method to check if file is excel file
        /// 
        /// 
        /// 
        private bool CheckIfExcelFile(IFormFile file)
        {
            var extension = "." + file.FileName.Split('.')[file.FileName.Split('.').Length - 1];
            return (extension == ".xlsx" || extension == ".xls"); // Change the extension based on your need
        }

        private async Task<bool> WriteFile(IFormFile file)
        {
            bool isSaveSuccess = false;
            string fileName;
            try
            {
                var extension = "." + file.FileName.Split('.')[file.FileName.Split('.').Length - 1];
                fileName = DateTime.Now.Ticks + extension; //Create a new Name for the file due to security reasons.

                var pathBuilt = Path.Combine(Directory.GetCurrentDirectory(), "Upload\\files");

                if (!Directory.Exists(pathBuilt))
                {
                    Directory.CreateDirectory(pathBuilt);
                }

                var path = Path.Combine(Directory.GetCurrentDirectory(), "Upload\\files",
                   fileName);

                using (var stream = new FileStream(path, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }

                isSaveSuccess = true;
            }
            catch (Exception e)
            {
               //log error
            }

            return isSaveSuccess;
        }
    }
}

GitHub Code

You can get the complete code from github https://github.com/karthiktechblog/UploadFileUsingDotNETCore

Reference

Read more about IFormFile Interface
To upload multiple files, use IFormFileCollection Interface

Related Posts

Conclusion

In this post, I showed how to upload a file with .NET CORE Web API 3.1 using IFormFile. That’s all from this post. If you have any questions or just want to chat with me, feel free to leave a comment below.

The post How to upload a file with .NET CORE Web API 3.1 using IFormFile appeared first on Learn Smart Coding.

]]>
https://blogs.learnsmartcoding.com/2020/04/04/how-to-upload-a-file-with-net-core-web-api-3-1-using-iformfile/feed/ 0 434
How to upload a file in ASP.NET Web API https://blogs.learnsmartcoding.com/2020/04/04/how-to-upload-a-file-in-asp-net-web-api/ https://blogs.learnsmartcoding.com/2020/04/04/how-to-upload-a-file-in-asp-net-web-api/#respond Sat, 04 Apr 2020 15:18:07 +0000 https://karthiktechblog.com/?p=430 In this short post, I will show how to upload a file in ASP.NET Web API. In this example, I will be using FormData to upload a file from any UI technology like JavaScript, Angular and much more. Using FormData FormData provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send() method. The form uses “multipart/form-data” as encoding type and FormData does the same. […]

The post How to upload a file in ASP.NET Web API appeared first on Learn Smart Coding.

]]>
In this short post, I will show how to upload a file in ASP.NET Web API. In this example, I will be using FormData to upload a file from any UI technology like JavaScript, Angular and much more.

Using FormData

FormData provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the XMLHttpRequest.send() method.

The form uses “multipart/form-data” as encoding type and FormData does the same.

Let’s jump into the coding part to see how to upload a file in ASP.NET Web API.

Upload Example

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;

namespace KarthikTechBlog.API.Controllers
{
    public class UploadController : ApiController
    {
        private readonly string uploadPath ="~/App_Data/uploads";
        private readonly List allowedFileExtensions = new List() { "pdf", "xlx", "doc", "docx", "xlxs" };

        [HttpPost]
        [ActionName("UploadFile")]
        public async Task UploadFile()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
            
            var provider = new MultipartMemoryStreamProvider();

            await Request.Content.ReadAsMultipartAsync(provider);

            var file = provider.Contents.FirstOrDefault();

            var fileExtension = file.Headers.ContentDisposition.FileName.Split('.')[1];
            if (!allowedFileExtensions.Any(a => a.Equals(fileExtension)))
            {
                return BadRequest($"File with extension {fileExtension} is not allowed");
            }

            await SaveFileToDisc(file, fileExtension); 
            
            await SaveFileToDatabase(file);

            return Ok();
        }

        private async Task SaveFileToDisc(HttpContent file, string extension)
        {
            var fileName = $"{DateTime.Now.Ticks}.{extension}"; 

            var root = System.Web.HttpContext.Current.Server.MapPath(uploadPath);

            var pathBuilt = Path.Combine(root, string.Concat(DateTime.Now.Month.ToString(), DateTime.Now.Day.ToString(), DateTime.Now.Year.ToString()));

            if (!Directory.Exists(pathBuilt))
            {
                Directory.CreateDirectory(pathBuilt);
            }

            var path = Path.Combine(pathBuilt, fileName);

            using (var stream = new FileStream(path, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }
        }

        private async Task SaveFileToDatabase(HttpContent file)
        {
            var byteArray = await file.ReadAsByteArrayAsync();
            var base64String = Convert.ToBase64String(byteArray); // Save this base64 string to database
        }

    }
}

With upload functionality, you can save the incoming file to a disc or save the file to a database after encoding the file to standard Base64 string. You may also perform both operations like saving the file to disc and to the database.

Are you looking for similar upload functionality in ASP NET CORE 3.1? Read this post for more details.

Reference

to read more about MultipartMemoryStreamProvider, visit MultipartStreamProvider Class in MSDN

Related Posts

Conclusion

In this post, I showed how to upload a file in ASP.NET Web API. That’s all from this post. If you have any questions or just want to chat with me, feel free to leave a comment below.

The post How to upload a file in ASP.NET Web API appeared first on Learn Smart Coding.

]]>
https://blogs.learnsmartcoding.com/2020/04/04/how-to-upload-a-file-in-asp-net-web-api/feed/ 0 430