0

I have a UrlRewrite rule, which looks like this:

<rewrite>
    <rules>             
        <rule name="Add prefix to pictures request" stopProcessing="true">
          <match url="^pictures/(.*)" />
          <action type="Rewrite" url="/pictures/pictures-dev/{R:1}" appendQueryString="true" logRewrittenUrl="true" />
        </rule>
    </rules>
</rewrite>

The idea is to add some kind of a prefix to original request (in this case, the prefix is /pictures/pictures-dev/. Later this rewritten request is processed by a plugin and not handled by my code. The /pictures endpoint is the main endpoint for such requests. The rewrite rule is vital, and without the rule applied the request won't be processed.

Also I have a controller named ImagesController, which has a single method Get. This method should act like the /pictures endpoint, but does some additional processing. The only thing is important that /images endpoint cannot issue client-side redirect (HTTP 301) by design.

So, it is desired to redirect all requests from /images to /pictures. Due to additional processing, I cannot simply redirect requests from /images to /pictures.

To achieve this, I've done the following in the ImagesController:

[System.Web.Http.HttpGet]
public IHttpActionResult Get(long id)
{
     // Some work to be done here
     // ....
     // TransferRequest does not return in case of successful request
     HttpContext.Current.Server.TransferRequest($"~/pictures/{id}", true);

     return null;
 }

As I've found a lot about TransferRequest, this method should re-run the whole IIS request stack, so I suppose UrlRewrite should also be executed.

I expect "pictures/{id}" to be rewritten into "/pictures/pictures-dev/{id}". However, I see that "/pictures/{id}" issued by TransferRequest is not rewritten, which makes me think that UrlRewrite module is not executed against this "transferred" request.

What am I missing? Or maybe there are other ways to achieve this?

Thanks!

kralfy
  • 7
  • 4
  • You are missing the fact that `TransferRequest` and URL rewriting is totally unnecessary in MVC because you can use *routing* to do the same thing (only better). URL rewriting takes a URL and writes it to another URL, which it then passes onto the handler. Routing sends a request *directly* to a handler without any faking of URLs. You need to cut out the middle-man and just use routing. See [Can an ASP.NET MVC controller return an Image?](http://stackoverflow.com/q/186062/181087). – NightOwl888 Jul 11 '16 at 13:09
  • @NightOwl888 Well, I need to execute some code in **ImagesController.Get** method before redirect. If I hadn't to, I'd definitely use routing options. Also I'm not in control of **/pictures** endpoint because it's handled by a plugin, and it is vital to use this endpoint finally. – kralfy Jul 11 '16 at 13:50

0 Answers0