Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can't do this "out of the box" with the MVC framework. Remember that there is a difference between Routing and URL-rewriting. Routing is mapping every request to a resource, and the expected resource is a piece of code.</p> <p>However - the flexibility of the MVC framework allows you to do this with no real problem. By default, when you call <code>routes.MapRoute()</code>, it's handling the request with an instance of <code>MvcRouteHandler()</code>. You can build a <em>custom</em> handler to handle your image urls.</p> <ol> <li><p>Create a class, maybe called ImageRouteHandler, that implements <code>IRouteHandler</code>.</p></li> <li><p>Add the mapping to your app like this:</p> <p><code>routes.Add("ImagesRoute", new Route("graphics/{filename}",<br> new ImageRouteHandler()));</code></p></li> <li><p>That's it.</p></li> </ol> <p>Here's what your <code>IRouteHandler</code> class looks like:</p> <pre><code>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using System.Web.Compilation; using System.Web.Routing; using System.Web.UI; namespace MvcApplication1 { public class ImageRouteHandler : IRouteHandler { public IHttpHandler GetHttpHandler(RequestContext requestContext) { string filename = requestContext.RouteData.Values["filename"] as string; if (string.IsNullOrEmpty(filename)) { // return a 404 HttpHandler here } else { requestContext.HttpContext.Response.Clear(); requestContext.HttpContext.Response.ContentType = GetContentType(requestContext.HttpContext.Request.Url.ToString()); // find physical path to image here. string filepath = requestContext.HttpContext.Server.MapPath("~/test.jpg"); requestContext.HttpContext.Response.WriteFile(filepath); requestContext.HttpContext.Response.End(); } return null; } private static string GetContentType(String path) { switch (Path.GetExtension(path)) { case ".bmp": return "Image/bmp"; case ".gif": return "Image/gif"; case ".jpg": return "Image/jpeg"; case ".png": return "Image/png"; default: break; } return ""; } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload