Return jpeg image from Asp.Net Core WebAPI

Clean solution use FilestreamResult !! [HttpGet] public IActionResult Get() { var image = System.IO.File.OpenRead(“C:\\test\\random_image.jpeg”); return File(image, “image/jpeg”); } Explanation: In ASP.NET Core you have to use the built-in File() method inside the Controller. This will allow you to manually set the content type. Don’t create and return HttpResponseMessage, like you were used to using in … Read more

Unit testing controller methods which return IActionResult

Assuming something like the public IActionResult GetOrders() { var orders = repository.All(); return Ok(orders); } the controller in this case is returning an OkObjectResult class. Cast the result to the type of what you are returning in the method and perform your assert on that [Fact] public void GetOrders_WithOrdersInRepo_ReturnsOk() { // arrange var controller = … Read more

Returning a 404 from an explicitly typed ASP.NET Core API controller (not IActionResult)

This is addressed in ASP.NET Core 2.1 with ActionResult<T>: public ActionResult<Thing> Get(int id) { Thing thing = GetThingFromDB(); if (thing == null) return NotFound(); return thing; } Or even: public ActionResult<Thing> Get(int id) => GetThingFromDB() ?? NotFound(); I’ll update this answer with more detail once I’ve implemented it. Original Answer In ASP.NET Web API 5 … Read more

How to return a specific status code and no contents from Controller?

this.HttpContext.Response.StatusCode = 418; // I’m a teapot How to end the request? Try other solution, just: return StatusCode(418); You could use StatusCode(???) to return any HTTP status code. Also, you can use dedicated results: Success: return Ok() ← Http status code 200 return Created() ← Http status code 201 return NoContent(); ← Http status code … Read more

Return file in ASP.Net Core Web API

If this is ASP.net-Core then you are mixing web API versions. Have the action return a derived IActionResult because in your current code the framework is treating HttpResponseMessage as a model. [Route(“api/[controller]”)] public class DownloadController : Controller { //GET api/download/12345abc [HttpGet(“{id}”)] public async Task<IActionResult> Download(string id) { Stream stream = await {{__get_stream_based_on_id_here__}} if(stream == null) … Read more

ASP.NET Core return JSON with status code

The most basic version responding with a JsonResult is: // GET: api/authors [HttpGet] public JsonResult Get() { return Json(_authorRepository.List()); } However, this isn’t going to help with your issue because you can’t explicitly deal with your own response code. The way to get control over the status results, is you need to return a ActionResult … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)