3
On a project I’m working on, I wrote a HttpHandler
to bring as a response an image instead of a View, sort of like this:
using System;
using System.Web;
using System.Web.Routing;
using MeuProjeto.Data;
using MeuProjeto.Infrastructure;
namespace MeuProjeto.HttpHandlers
{
public class ImagemFuncionarioHttpHandler : IHttpHandler
{
public RequestContext RequestContext { get; set; }
public ImagemFuncionarioHttpHandler(RequestContext requestContext)
{
RequestContext = requestContext;
}
/// <summary>
///
/// </summary>
public bool IsReusable
{
get { return false; }
}
/// <summary>
///
/// </summary>
/// <param name="context"></param>
public void ProcessRequest(HttpContext context)
{
var currentResponse = HttpContext.Current.Response;
currentResponse.ContentType = "image/jpeg";
currentResponse.Buffer = true;
var usuarioId = Convert.ToInt32(RequestContext.RouteData.GetRequiredString("id"));
try
{
var funcionario = new Funcionarios(GeneralSettings.DataBaseConnection).SelecionarPorId(usuarioId);
currentResponse.BinaryWrite(funcionario.ThumbnailFuncionario);
currentResponse.Flush();
}
catch (Exception ex)
{
context.Response.Write(ex.StackTrace);
}
}
}
}
To run a route, this HttpHandler
needs a RouteHandler
:
using System.Web;
using System.Web.Routing;
using MeuProjeto.HttpHandlers;
namespace MeuProjeto.RouteHandlers
{
public class ImagemFuncionarioRouteHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
return new ImagemFuncionarioHttpHandler(requestContext);
}
}
}
And the route configuration looks like this:
using System.Web.Mvc;
using System.Web.Routing;
using MeuProjeto.Helpers;
using MeuProjeto.RouteHandlers;
namespace MeuProjeto
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.Add(new Route("Funcionarios/Thumbnail/{id}", new ImagemFuncionarioRouteHandler()));
routes.MapRouteWithName(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
The above code works perfectly if I enter the following address:
Only every time I use the route on whatever screen it is, the actions
of forms
spoil by redirecting the POST request to this address http://meudominio.com.br/Funcionarios/Thumbnail/1?action=Index&controller=Vagas
.
What should I do?
I’m sorry, Gypsy, but I don’t quite understand. You call through the link "http://meudominio.com.br/Functions/Thumbnail/1" and redirect the POST to the same link?
– Reiksiel
No. This link gives me an image that’s in the database, and that’s it. The
<form>
points correctly to/Vagas/Edit/123
, for example, but inPOST
the result will mysteriously stop atThumbnail
.– Leonel Sanches da Silva
Gypsy, if using Asp.net MVC 5, try this to see if you can resolve... http://goo.gl/bl1W0w
– Hermes Autran
I have done it. I think the answer is still given today.
– Leonel Sanches da Silva