Streaming files using HTTP GET : ASP .NET CORE API - c#

I have written a controller to download/stream file to the clients local machine. The code doesn't stream the file on doing a GET to the url besides only produces response body.
What is the problem with streamcontent method. On debug i could not find the issue.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using System.Net.Http;
using System.Net;
using System.IO;
using System.Text;
namespace FileDownloaderService.Controllers
{
[Route("api/[controller]")]
public class FileDownloadController : Controller
{
[HttpGet]
public HttpResponseMessage Get() {
string filename = "ASPNETCore" + ".pdf";
string path = #"C:\Users\INPYADAV\Documents\LearningMaterial\"+ filename;
if (System.IO.File.Exists(path)) {
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(path, FileMode.Open);
stream.Position = 0;
result.Content = new StreamContent(stream);
result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = filename };
result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");
result.Content.Headers.ContentDisposition.FileName = filename;
return result;
}
else
{
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.Gone);
return result;
}
}
}
}
Response:
{"version":{"major":1,"minor":1,"build":-1,"revision":-1,"majorRevision":-1,"minorRevision":-1},"content":{"headers":[{"key":"Content-Disposition","value":["attachment; filename=ASPNETCore.pdf"]},{"key":"Content-Type","value":["application/pdf"]}]},"statusCode":200,"reasonPhrase":"OK","headers":[],"requestMessage":null,"isSuccessStatusCode":true}

In ASP.NET Core, you need to be using an IActionResult if you are sending a custom response. All other responses will be serialized (JSON by default) and sent as response body.
Refer to the answer at File Streaming in ASP.NET Core

Related

How can i get Headers value with Net Core?

I send a request on the API, the request and the response are successful, but I want to get the value equivalent to the authentication keyword through the response. How can I do that? I tried this way on the examples I found, but it doesn't give any results .Net 6.0
using LoggerApi.Login;
using System;
using System.Net.Http;
using System.Text;
using Newtonsoft.Json;
using System.Linq;
using Microsoft.Extensions.Primitives;
namespace LoggerApi.Login
{
public class AdminLogin
{
public async static Task<object> GetAuthenticationCode()
{
var client = new HttpClient();
var loginEndpoint = new Uri("https://admin.com/login");
var loginPayload = new LoginPayload()
{
Username = "admin",
Password= "admin",
};
var requestJson = JsonConvert.SerializeObject(loginPayload);
var payload = new StringContent(requestJson, Encoding.UTF8, "application/json");
var res = await client.PostAsync(loginEndpoint, payload).Result.Headers.TryGetValues("authentication");
return res;
}
}
}

PostAsJsonAsync it's not posting

i had created a code to insert a product item into my API, but its not working, i had tried to do manually using the PostMan and just made it, the status is allways 201 - created, im using .net 6
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Text.Json;
using WebApplication1.Data;
using WebApplication1.Models;
using (var httpClient = new HttpClient())
{
Item_Produtos item = new Item_Produtos();
item.Id = 10;
item.Produto_Id = 109;
item.PedidoVenda_Id = 15283;
item.qtdItem = 1;
item.vlPreco = 109;
item.Item_Obs = "";
item.Opcao_Obs = "Tamanho:M=1;|Cor:Especial=1;|";
item.Store_Id = 27;
item.vlSubTotal = 109;
using HttpClient client = new()
{
BaseAddress = new Uri("api/adress-here")
};
HttpResponseMessage response = await client.PostAsJsonAsync("carrinho", item);
Console.WriteLine(
$"{(response.IsSuccessStatusCode ? "Success" : "Error")} - {response.StatusCode}");
} ```
I solved my problem by separating some steps, at first converting into a Json then into a string Content, and then instead of use the PostAsJsonAsync i used the PostAsync with the new format
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Text.Json;
using WebApplication1.Data;
using WebApplication1.Models;
using System.Text;
using HttpClient client = new(){
BaseAddress = new Uri("api/adress-here")
};
var json = JsonSerializer.Serialize(item);
var data = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync("carrinho", data);

How to download a PDF from URL with C# API Controller (ASP.NET)

Built basic API controller that downloads a PDF file that is stored locally within the project.
Is there a way to modify the code so that the PDF can be downloaded from a URL link?
I've tried the different methods that are available to use in the HostingEnvironment Class.
Here is an example:
DownloadController.cs
using System.IO;
using System.Net.Http;
using System.Web.Hosting;
using System.Web.Http;
namespace DownloadAPITest.Controllers
{
public class DownloadController : ApiController
{
public HttpResponseMessage Get()
{
HttpResponseMessage result = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
//string pdfLocation = HostingEnvironment.MapPath("~/Content/SE_SurfaceWater_Tbl.pdf");
//string pdfLocation = HostingEnvironment.MapPath("http://***.***.local/ReportServer?/proj_20800014/SE_SurfaceWater_Tbl&rs:Command=Render&rs:Format=PDF");
string pdfLocation = HostingEnvironment.
var stream = new MemoryStream(System.IO.File.ReadAllBytes(pdfLocation));
stream.Position = 0;
if (stream == null)
return Request.CreateResponse(System.Net.HttpStatusCode.NotFound);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("inline"); //"inline" to make it appear on the browser //"attachment" for direct download
result.Content.Headers.ContentDisposition.FileName = "fileTest.pdf";
result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");
result.Content.Headers.ContentLength = stream.Length;
return result;
}
}
}

How to properly do this C# MultiPartFormDataContent API Call?

I am currently trying to make an api call in c# using a MultiPartFormDataContent but I keep
getting the following error:
"Response: {"statusCode":400,"error":"Bad Request","message":""Image file" must be of type object","validation":{"source":"payload","keys":["images"]}}"
This is my Code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace Example
{
public class Test
{
public static void Main(string[] args)
{
Task<string> test = testFunction();
Console.WriteLine("Result: " + test.Result);
}
public static async Task<string> testFunction()
{
const string file = "C:\\ExamplePath\\image_1.jpeg";
const string URL = "https://example-api?api-key=example-key";
string boundary = "---8d0f01e6b3b5dafaaadaad";
MultipartFormDataContent multipartContent = new MultipartFormDataContent(boundary);
var streamContent = new StreamContent(File.Open(file, FileMode.Open));
var stringContent = new StringContent("flower");
multipartContent.Add(stringContent, "organs");
multipartContent.Add(streamContent, "images");
try
{
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.PostAsync(URL, multipartContent);
Console.WriteLine("Response: " + await response.Content.ReadAsStringAsync());
if (response.IsSuccessStatusCode)
{
string content = await response.Content.ReadAsStringAsync();
Console.WriteLine("IN METHIOD: " + content);
return content;
}
return null;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return null;
}
}
}
}
It's obviously a problem with how I am trying to do the api call but I don't know how to do it with an object instead like mentioned the error message.
This link has some good examples and where I actually got my code snippet from below.
Here's a basic example of using MultiFormDataContent:
HttpClient httpClient = new HttpClient();
MultipartFormDataContent form = new MultipartFormDataContent();
form.Add(new StringContent(username), "username");
form.Add(new StringContent(useremail), "email");
form.Add(new StringContent(password), "password");
form.Add(new ByteArrayContent(file_bytes, 0, file_bytes.Length), "profile_pic", "hello1.jpg");
HttpResponseMessage response = await httpClient.PostAsync("PostUrl", form);
response.EnsureSuccessStatusCode();
httpClient.Dispose();
string sd = response.Content.ReadAsStringAsync().Result;
I hope this helps or points you in the right direction.

C# Web API code read a file and open the file when return

I was able using the following C# Web Api 2 code to fetch a file from a path and download the file. User is able to download abc.pdf by using this url http://localhost:60756/api/TipSheets/GetTipSheet?fileName=abc.pdf . I would like to make code change to open the file instead of downloading the file. How can I do that ?
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Mvc;
using HttpGetAttribute = System.Web.Http.HttpGetAttribute;
namespace TestWebApi.Controllers
{
public class TipSheetsController : ApiController
{
string tipSheetPath = #"C:\pdf\";
string videoPath = #"C:\video\";
string clientIp;
string clientIpSrc;
public IHttpActionResult GetTipSheet(string fileName)
{
string ext = Path.GetExtension(fileName).ToLowerInvariant();
string reqBook = (ext.Equals(".pdf")) ? tipSheetPath + fileName : videoPath +
fileName;
//string bookName = fileName;
//converting Pdf file into bytes array
try
{
var dataBytes = File.ReadAllBytes(reqBook);
//adding bytes to memory stream
var dataStream = new MemoryStream(dataBytes);
return new tipSheetResult(dataStream, Request, fileName);
}
catch (Exception)
{
throw;
}
}
}
public class tipSheetResult : IHttpActionResult
{
MemoryStream bookStuff;
string PdfFileName;
HttpRequestMessage httpRequestMessage;
HttpResponseMessage httpResponseMessage;
public tipSheetResult(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.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);
}
}
}

Categories