Iliya Krinchiyan Iliya Krinchiyan - 2 months ago 34
C# Question

Redirect to external URL with custom schema

I have Asp.net MVC4 project. I want to make redirect to the external url if specified action is called.
Url should have custom schema, for example not

http://
but
myschema://
.

I know that to redirect to google.com I can use
return Redirect("http://google.com")
, but this doesn't work if I call
return Redirect("myschema://someaddress.com")


I need this custom schema to start app on IOS device and I need to do redirection in MVC project because I want to send link to email, this link will lead to action on my site and this action will do redirect to custom schema.

Sending link with custom schema directly in mail is not working because mail servers delete this link from the mail.
Also I don't want to redirect user to the frontend where he will need to click to the link with custom schema.

Is it possible or should I do it in other way?

Answer

you can create a custom RedirectResult. If you dig through the source code of the asp.net mvc RedirectResult you can work out pretty quickly what it's doing.

Here's one I banged out pretty quick.

public class RedirectResult : ActionResult
{
    private string _url;

    public RedirectResult(string url)
    {
        _url = url;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
            throw new ArgumentNullException("context");

        string url = UrlHelper.GenerateContentUrl(_url, context.HttpContext);
        context.Controller.TempData.Keep();
        HttpResponseBase response = context.HttpContext.Response;
        response.RedirectPermanent(url, endResponse: true);

    }
}

On Fiddler this now does:

HTTP/1.1 301 Moved Permanently
Date: Tue, 11 Feb 2014 14:03:39 GMT
X-AspNet-Version: 4.0.30319
X-AspNetMvc-Version: 3.0
Location: myschema://someaddress.com
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Length: 149
Connection: Close