In the project in which I work, I wrote HttpHandlerto bring as an answer an image instead of a presentation, for example:
using System;
using System.Web;
using System.Web.Routing;
using MyProject.Data;
using MyProject.Infrastructure;
namespace MyProject.HttpHandlers
{
public class PersonImageHttpHandler : IHttpHandler
{
public RequestContext RequestContext { get; set; }
public PersonImageHttpHandler(RequestContext requestContext)
{
RequestContext = requestContext;
}
public bool IsReusable
{
get { return false; }
}
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 person = new People(GeneralSettings.DataBaseConnection).SelectPorId(usuarioId);
currentResponse.BinaryWrite(person.Thumbnail);
currentResponse.Flush();
}
catch (Exception ex)
{
context.Response.Write(ex.StackTrace);
}
}
}
}
This HttpHandlerrequires RouteHandler:
using System.Web;
using System.Web.Routing;
using MyProject.HttpHandlers;
namespace MyProject.RouteHandlers
{
public class PersonImageRouteHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
return new PersonImageHttpHandler(requestContext);
}
}
}
Routes.cs something like that:
using System.Web.Mvc;
using System.Web.Routing;
using MyProject.Helpers;
using MyProject.RouteHandlers;
namespace MyProject
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.Add(new Route("People/Thumbnail/{id}", new PersonImageRouteHandler()));
routes.MapRouteWithName(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
Works like a charm, addressing the following address
http://mydomain.com/People/Thumbnail/1
But every time I use some query for this route, actionsfrom formsnot working, POST request forwarding to this address: http://mydomain.com/People/Thumbnail/1?action=Index&controller=AnotherController.
What's wrong?
source
share