使用自定义架构重定向到外部URL

时间:2014-01-16 11:55:40

标签: c# ios asp.net-mvc asp.net-mvc-4

我有Asp.net MVC4项目。如果调用了指定的动作,我想重定向到外部URL。 网址应具有自定义架构,例如,不是http://,而是myschema://

我知道要重定向到google.com我可以使用return Redirect("http://google.com"),但如果我拨打return Redirect("myschema://someaddress.com")

,这不起作用

我需要这个自定义架构来启动IOS设备上的应用程序,我需要在MVC项目中进行重定向,因为我想发送链接到电子邮件,此链接将导致我的网站上的操作,此操作将重定向到自定义架构

直接在邮件中发送带有自定义架构的链接无效,因为邮件服务器会从邮件中删除此链接。 此外,我不想将用户重定向到前端,他需要点击自定义架构的链接。

是否有可能或应该以其他方式进行?

2 个答案:

答案 0 :(得分:1)

您可以创建自定义RedirectResult。如果你深入了解asp.net mvc RedirectResult的源代码,你可以很快地解决它正在做的事情。

这是我很快就打败的一个。

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);

    }
}

在Fiddler现在这样做:

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

答案 1 :(得分:0)

今天早上我有同样的问题。我会设置一个字符串:

string myUrl = "mySchema:parameters";

并在电话中致电:

return Redirect(myUrl);

我不会看到重定向发生。

我尝试创建一个继承自RedirectResult的自定义类(请注意RedirectResultSystem.Net.Mvc中提供的类),类似于@ DaveWalker的回答,但这对我没有任何影响。

在敲了几个小时之后,我决定在一个真实的移动设备上测试这个电话:瞧,重定向在那里正确发生。

与移动设备相比,这可能与PC浏览器的实现方式有关。

所以,总结一下,即使在PC浏览器上看不到,也要做

return Redirect(urlWithCustomSchema);

在移动设备上运行良好。