asp.net - 如何在线程内生成 ActionLink

标签 asp.net asp.net-mvc asp.net-mvc-2

我有一个发送电子邮件的线程。我需要生成 ActionLinks 作为电子邮件内容的一部分,以便用户可以单击链接并重定向到网站,准确地转到所需的页面。我尝试实例化一个 UrlHelper 类并使用它的 Action 方法来生成链接,但由于线程不在任何请求的上下文中运行,所以我在生成 ActionLink。

我该怎么做?

最佳答案

您需要伪造 HttpContextBase 并将其传递给 UrlHelper,您可以在没有 HttpContext 的线程中使用它。这是粗略的想法,尽管您需要围绕它创建一个类等,但这是一个快速的概念证明,因为单元测试也没有 HttpContext。

[TestFixture]
public class RouteTestClass
{
    private UrlHelper helper;

    public RouteTestClass()
    {
        MvcApplication.RegisterRoutes(RouteTable.Routes); //You dont need to do this if its done in global.asax!
        var c = new RequestContext(new FakeContext(), new RouteData());
        helper = new UrlHelper(c, RouteTable.Routes);
    }

    [Test]
    public void TestGetHomeIndex()
    {
        var url = helper.Action("Index", "Home");
        Assert.AreEqual("/",url);
    }
}

public class FakeContext : HttpContextBase
{
    public override HttpRequestBase Request { get { return new FakeRequest(); } }
    public override HttpResponseBase Response { get { return new FakeResponse(); } }
}

public class FakeRequest : HttpRequestBase
{
    public override string ApplicationPath { get { return "/"; } }
    public override NameValueCollection ServerVariables { get { return new NameValueCollection(); } }
}

public class FakeResponse : HttpResponseBase
{
    public override string ApplyAppPathModifier(string virtualPath)
    {
        return virtualPath;
    }
}

编辑

查看this回答,我稍微整理了一下代码,因为我不需要自己为 HttpRequestBase 和 HttpResponseBase 创建假货。

[TestFixture]
public class RouteTestClass
{
    private UrlHelper helper;

    public RouteTestClass()
    {
        MvcApplication.RegisterRoutes(RouteTable.Routes);
        var req = new HttpRequest("/", "http://www.yoururl.com", "");
        var resp = new HttpResponse(new StringWriter());
        var httpContext = new HttpContext(req, resp);
        var c = new RequestContext(new HttpContextWrapper(httpContext), new RouteData());
        helper = new UrlHelper(c, RouteTable.Routes);
    }

    [Test]
    public void TestGetHomeIndex()
    {
        var url = helper.Action("Index", "Home");
        Assert.AreEqual("/",url);
    }
}

关于asp.net - 如何在线程内生成 ActionLink,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3702443/

相关文章:

javascript - Firebug 调试问题

html - 使用 CSS 文件进行站点本地化

asp.net-mvc-2 - 在自定义模型绑定(bind)器中设置 ModelState 值

c# - 字符串格式在本地而不是在服务器中工作

c# - 使用 javascript/jquery 计算两个值

asp.net-mvc - MVC 3 : displaying viewmodel items in a view

asp.net-mvc-2 - 如何在Asp.Net MVC 2中显示一般错误页面

c# - 如何向 css、javascript 添加根或基本 url?

c# - 使用 ExceptionHandler PipeLine 时,ASP.NET Core 返回 404 而不是 500

asp.net-mvc - ASP.NET MVC - *上下文模式象征什么?