ASP.NET Web APIからファイルを返す

前提条件

  • 基本的なC#コーディングの知識
  • WebAPIの最低限の知識
  • RESTサービスの理解

RESTサービスを使用する場合、ファイルの送信方法を理解することが非常に重要です。この記事では、Web APIサービスからファイル(PDF / Word / Excel)を返す方法について説明します。

HttpRESTサービスを介してファイルを転送するプロセスを段階的に説明します。

サービスリクエストに提供されたファイルタイプに基づいてファイルを送信する必要があると仮定します。たとえば、ファイルタイプをPDFとして送信する場合、Docを送信するとサービスはPDFファイルを返し、サービスはWordドキュメントを返します。(私はすべてのタイプのファイルをカバーするためにこのサンプルを取りました)。

元の状態からファイルを送信することはできません。ファイルをRESTサービスに送信するには、以下の手順に従う必要があります。

必要なファイルをバイトに変換する

最初に、ファイルクラス(System.IOからのもの)を使用してファイルをバイトに変換する必要があります

//converting Pdf file into bytes array  
var dataBytes = File.ReadAllBytes(reqBook);  

MemoryStreamへのバイトの追加

次に、 ファイルのバイト形式を渡して、MemoryStreamのインスタンスを作成します。

//adding bytes to memory stream   
var dataStream = new MemoryStream(dataBytes);  

 HttpResponseMessageコンテンツへのMemoryStreamオブジェクトの追加

最後のステップは、次のように、MemoryStream オブジェクトをHttpResponseMessage コンテンツに追加することです。

httpResponseMessage.Content = new StreamContent(bookStuff);  

HttpResponseMessageヘッダーのその他の必須の変更

ここでファイルを返すので、クライアントにサービスの内容を理解させるには、次のHttpResponseMessageヘッダープロパティを変更する必要があります。

  • ContentDisposition
  • ファイル名
  • ContentType

次のコードは、上記の3つのフィールドを実装するために使用されます。

httpResponseMessage.Content.Headers.ContentDisposition =  new  System.Net.Http.Headers.ContentDispositionHeaderValue("attachment" );  
httpResponseMessage.Content.Headers.ContentDisposition.FileName = PdfFileName;  
httpResponseMessage.Content.Headers.ContentType =  new  System.Net.Http.Headers.MediaTypeHeaderValue("application / octet-stream" );  

ここでContentTypeについて説明する必要があります。私はapplication / octet-streamを使用しましたが、一部の場所ではapplication / pdfを見ることができますが、なぜそれを使用したのですか?簡単に言えば、RESTサービスにファイルを送信していて、ファイルタイプがわからないが信頼できるものである場合、このような状況では、application / octet-streamを使用する必要があります。

ワンショットでコードを完成させる

IHttpActionResultとHttpResponseMessageのアクション結果を使用して記述しました。

public class EbookController : ApiController  
    {  
        string bookPath_Pdf = @"C:\MyWorkSpace\SelfDev\UserAPI\UserAPI\Books\sample.pdf";  
        string bookPath_xls = @"C:\MyWorkSpace\SelfDev\UserAPI\UserAPI\Books\sample.xls";  
        string bookPath_doc = @"C:\MyWorkSpace\SelfDev\UserAPI\UserAPI\Books\sample.doc";  
        string bookPath_zip = @"C:\MyWorkSpace\SelfDev\UserAPI\UserAPI\Books\sample.zip";  
  
        [HttpGet]  
        [Route("Ebook/GetBookFor/{format}")]  
        public IHttpActionResult GetbookFor(string format)  
        {  
            string reqBook = format.ToLower() == "pdf" ? bookPath_Pdf : (format.ToLower() == "xls" ? bookPath_xls : (format.ToLower() == "doc" ? bookPath_doc : bookPath_zip));  
            string bookName = "sample." + format.ToLower();  
  
            //converting Pdf file into bytes array  
            var dataBytes = File.ReadAllBytes(reqBook);  
            //adding bytes to memory stream   
            var dataStream = new MemoryStream(dataBytes);  
            return new eBookResult(dataStream, Request, bookName);  
        }  
        [HttpGet]  
        [Route("Ebook/GetBookForHRM/{format}")]  
        public HttpResponseMessage GetBookForHRM(string format)  
        {  
            string reqBook = format.ToLower() == "pdf" ? bookPath_Pdf : (format.ToLower() == "xls" ? bookPath_xls : (format.ToLower() == "doc" ? bookPath_doc : bookPath_zip));  
            string bookName = "sample." + format.ToLower();  
            //converting Pdf file into bytes array  
            var dataBytes = File.ReadAllBytes(reqBook);  
            //adding bytes to memory stream   
            var dataStream = new MemoryStream(dataBytes);  
  
            HttpResponseMessage httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);  
            httpResponseMessage.Content = new StreamContent(dataStream);  
            httpResponseMessage.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");  
            httpResponseMessage.Content.Headers.ContentDisposition.FileName = bookName;  
            httpResponseMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");  
  
            return httpResponseMessage;  
        }  
    }  
  
    public class eBookResult : IHttpActionResult  
    {  
        MemoryStream bookStuff;  
        string PdfFileName;  
        HttpRequestMessage httpRequestMessage;  
        HttpResponseMessage httpResponseMessage;  
        public eBookResult(MemoryStream data, HttpRequestMessage request, string filename)  
        {  
            bookStuff = data;  
            httpRequestMessage = request;  
            PdfFileName = filename;  
        }  
        public System.Threading.Tasks.Task<HttpResponseMessage> ExecuteAsync(System.Threading.CancellationToken cancellationToken)  
        {  
            httpResponseMessage = httpRequestMessage.CreateResponse(HttpStatusCode.OK);  
            httpResponseMessage.Content = new StreamContent(bookStuff);  
            //httpResponseMessage.Content = new ByteArrayContent(bookStuff.ToArray());  
            httpResponseMessage.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");  
            httpResponseMessage.Content.Headers.ContentDisposition.FileName = PdfFileName;  
            httpResponseMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");  
  
            return System.Threading.Tasks.Task.FromResult(httpResponseMessage);  
        }  
    }  

結果

プロジェクトを実行し、次のURLを使用してすべての形式のすべての書籍をダウンロードしようとしました(システムでコードを実行すると、IPが変更される場合があります)。

  • http:// localhost:59217 / api / Ebook / GetBookFor?format = pdf
  • http:// localhost:59217 / api / Ebook / GetBookFor?format = doc
  • http:// localhost:59217 / api / Ebook / GetBookFor?format = xls
  • http:// localhost:59217 / api / Ebook / GetBookFor?format = zip

最初に、PDF形式の値をサービスに送信し、それに応じてPDFファイルを取得しました。



後で、Word文書をリクエストしました。



添付のソースコードの実行方法(添付のプロジェクトでこの記事を練習したい場合は、このセクションを参照してください)

(プロジェクトのサイズのために)実際のフォルダー構造を持つ必要なファイルのみを添付しました。

以下の手順に従って、ファイル転送可能なWebAPIサービスを作成してください。

  • 添付のプロジェクトをダウンロードします。
  • Visual Studioを開き、新しいWebAPIプロジェクトを作成します。
  • プロジェクトのルートレベルにBookフォルダーを作成します。
  • サンプルのpdf、word、excel、zip(サンプルとして名前を付ける)ファイルを追加します。

    NS#

     
  • 新しいAPIコントローラーを作成し、ダウンロードしたプロジェクトからEbookControllerのコンテンツをコピーします。
  • 新しく作成したコントローラーのブックパス文字列を変更してください。
  • 次のコードをWebAPIConfig.csに追加します
config.Routes.MapHttpRoute(
   name: "FileServiceRoute”,  
   routeTemplate: “api / {controller}/{action}/ {id}”,
   defaults: new {id = RouteParameter.Optional}
);  
  • プロジェクトを再構築して実行します。
  • プロジェクトIPで上記のURLのいずれかを実行します

URLを実行すると、ファイルのダウンロードを確認できます。

リンク: https://www.c-sharpcorner.com/article/sending-files-from-web-api/

#webapi 

What is GEEK

Buddha Community

ASP.NET Web APIからファイルを返す
Einar  Hintz

Einar Hintz

1602560783

jQuery Ajax CRUD in ASP.NET Core MVC with Modal Popup

In this article, we’ll discuss how to use jQuery Ajax for ASP.NET Core MVC CRUD Operations using Bootstrap Modal. With jQuery Ajax, we can make HTTP request to controller action methods without reloading the entire page, like a single page application.

To demonstrate CRUD operations – insert, update, delete and retrieve, the project will be dealing with details of a normal bank transaction. GitHub repository for this demo project : https://bit.ly/33KTJAu.

Sub-topics discussed :

  • Form design for insert and update operation.
  • Display forms in modal popup dialog.
  • Form post using jQuery Ajax.
  • Implement MVC CRUD operations with jQuery Ajax.
  • Loading spinner in .NET Core MVC.
  • Prevent direct access to MVC action method.

Create ASP.NET Core MVC Project

In Visual Studio 2019, Go to File > New > Project (Ctrl + Shift + N).

From new project window, Select Asp.Net Core Web Application_._

Image showing how to create ASP.NET Core Web API project in Visual Studio.

Once you provide the project name and location. Select Web Application(Model-View-Controller) and uncheck HTTPS Configuration. Above steps will create a brand new ASP.NET Core MVC project.

Showing project template selection for .NET Core MVC.

Setup a Database

Let’s create a database for this application using Entity Framework Core. For that we’ve to install corresponding NuGet Packages. Right click on project from solution explorer, select Manage NuGet Packages_,_ From browse tab, install following 3 packages.

Showing list of NuGet Packages for Entity Framework Core

Now let’s define DB model class file – /Models/TransactionModel.cs.

public class TransactionModel
{
    [Key]
    public int TransactionId { get; set; }

    [Column(TypeName ="nvarchar(12)")]
    [DisplayName("Account Number")]
    [Required(ErrorMessage ="This Field is required.")]
    [MaxLength(12,ErrorMessage ="Maximum 12 characters only")]
    public string AccountNumber { get; set; }

    [Column(TypeName ="nvarchar(100)")]
    [DisplayName("Beneficiary Name")]
    [Required(ErrorMessage = "This Field is required.")]
    public string BeneficiaryName { get; set; }

    [Column(TypeName ="nvarchar(100)")]
    [DisplayName("Bank Name")]
    [Required(ErrorMessage = "This Field is required.")]
    public string BankName { get; set; }

    [Column(TypeName ="nvarchar(11)")]
    [DisplayName("SWIFT Code")]
    [Required(ErrorMessage = "This Field is required.")]
    [MaxLength(11)]
    public string SWIFTCode { get; set; }

    [DisplayName("Amount")]
    [Required(ErrorMessage = "This Field is required.")]
    public int Amount { get; set; }

    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
    public DateTime Date { get; set; }
}

C#Copy

Here we’ve defined model properties for the transaction with proper validation. Now let’s define  DbContextclass for EF Core.

#asp.net core article #asp.net core #add loading spinner in asp.net core #asp.net core crud without reloading #asp.net core jquery ajax form #asp.net core modal dialog #asp.net core mvc crud using jquery ajax #asp.net core mvc with jquery and ajax #asp.net core popup window #bootstrap modal popup in asp.net core mvc. bootstrap modal popup in asp.net core #delete and viewall in asp.net core #jquery ajax - insert #jquery ajax form post #modal popup dialog in asp.net core #no direct access action method #update #validation in modal popup

ASP.Net Web development Company USA | WebClues Infotech

A versatile Web & Mobile App Development framework technology that is fast, reliable, and easy to use is ASP.NET. ASP.NET gives the developer complete control over development and can be used on any project big or small.

Want to develop a website or mobile app with ASP.NET?

WebClues Infotech with years of experience and a highly skilled development team can be your go-to agency for your Web & Mobile App Development requirements. With an expert developer team of more than 150+ members, WebClues Infotech has successfully delivered more than 1500 projects worldwide.

Want to know more about the ASP.NET framework?

Visit: https://www.webcluesinfotech.com/asp-net-web-development/

Share your requirements https://www.webcluesinfotech.com/contact-us/

View Portfolio https://www.webcluesinfotech.com/portfolio/

#asp.net web development company #asp.net web development company usa #asp.net development company in india #asp.net development company #.net software development company #hire asp.net developer

Hire ASP.Net Developers

Looking to outsource your asp dot net development requirement?

ASP.Net is a special feature of the DOT Net framework created by Microsoft. At HourlyDeveloper.io, we have a team of experienced ASP.Net developers who are experts in delivering custom solutions based on your business requirements. Hire ASP.Net Developers who will provide tailored solutions to facilitate your business growth.

Consult with experts: https://bit.ly/3fNpVqr

#hire asp.net developers #asp.net development company #asp.net development services #asp.net development #asp.net developer #asp.net

Einar  Hintz

Einar Hintz

1602564619

MVC User Registration & Login with ASP.NET Core Identity

User registration and authentication are mandatory in any application when you have little concern about privacy. Hence all most all application development starts with an authentication module. In this article, we will discuss the quickest way to use **ASP.NET Core Identity for User Login and Registration **in a new or existing MVC application.

Sub-topics discussed :

  • How to add ASP.NET Core Identity to MVC application.
  • Customize ASP.NET Core Identity.
  • Identity.UI Design Customization.
  • Next step.

Background

ASP.NET Core Identity is an API, which provides both user interface(UI) and functions for user authentication, registration, authorization, etc. Modules/ APIs like this will really be helpful and fasten the development process. It comes with ASP.NET Core Framework and used in many applications before. Which makes the API more dependable and trustworthy.

ASP.NET Core MVC with user authentication can easily be accomplished using Identity.UI. While creating the MVC project, you just need to select Authentication as Individual User Accounts.

Showing how to create an MVC application with ASP.NET Core Identity API

The rest will be handled by ASP.NET Core Identity UI. It already contains razor view pages and backend codes for an authentication system. But that’s not what we want in most of the cases. we want to customize ASP.NET Core Identity as per our requirement. That’s what we do here.

Create an ASP.NET Core MVC Project

First of all, I will create a brand new ASP.NET Core MVC application without any authentication selected. We could add ASP.NET Core Identity later into the project.

In Visual Studio 2019, Go to File > New > Project (Ctrl + Shift + N). From new project window, select ASP.NET Core Web Application.

Create an ASP.NET Core Web application

Once you provide the project name and location. A new window will be opened as follows, Select _Web Application(Model-View-Controller), _uncheck _HTTPS Configuration _and DO NOT select any authentication method. Above steps will create a brand new ASP.NET Core MVC project.

Select Model View Controller templet under .NET Core

#asp.net core article #asp.net core #add asp.net core identity to existing project #asp.net core identity in mvc #asp.net core mvc login and registration #login and logout in asp.net core

Jamal  Lemke

Jamal Lemke

1600056000

Blazor for ASP.NET Web Forms Developers PDF

Blazor is a new web framework that changes what is possible when building web apps with .NET. It is also a client-side web UI framework based on C## instead of JavaScript. When paired with .NET running on the server, Blazor enables full-stack web development with .NET.

It also builds on the foundations of .NET Core to provide a modern and high-performance web development experience. Additionally, Blazor is a natural solution for ASP.NET Web Forms developers looking to take advantage of client-side development and the open-source, cross-platform future of .NET.

This e-book pdf covers the following ASP.NET Web Forms features and practices:-

  • Building Blazor apps.
  • How Blazor works.
  • Blazor’s relation to .NET Core.
  • Reasonable strategies for migrating existing ASP.NET Web Forms apps to Blazor where appropriate.
  • A reference sample that demonstrates the migration strategies used.

#articles #asp.net #blazor #blazor for asp.net web forms #blazor for asp.net web forms developers #blazor web forms #convert web forms to blazor