在子站点中使用邮政和Hangfire [英] Using Postal and Hangfire in Subsite

查看:90
本文介绍了在子站点中使用邮政和Hangfire的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图在我的MVC5网站上使用Postal.当我在网页上托管一个子站点时,即 http://localhost/Subsite ,我收到错误

I have been trying to use Postal on my MVC5 site. When I host my webpage a subsite ie, http://localhost/Subsite I am receiving the error

  • 虚拟路径'/'映射到另一个应用程序,这是不允许的

我已将其调试为在创建ControllerContext时未正确设置HttpContext.由于我是从Hangfire运行邮政,因此HttpContext.Current始终为null.邮政使用下面的代码创建ContollerContext.

I have debugged it down to when the ControllerContext is being created the HttpContext isn't getting set correctly. Since I'm running Postal from Hangfire the HttpContext.Current is always null. Postal creates the ContollerContext using the code below.

        ControllerContext CreateControllerContext()
    {
        // A dummy HttpContextBase that is enough to allow the view to be rendered.
        var httpContext = new HttpContextWrapper(
            new HttpContext(
                new HttpRequest("", UrlRoot(), ""),
                new HttpResponse(TextWriter.Null)
            )
        );
        var routeData = new RouteData();
        routeData.Values["controller"] = EmailViewDirectoryName;
        var requestContext = new RequestContext(httpContext, routeData);
        var stubController = new StubController();
        var controllerContext = new ControllerContext(requestContext, stubController);
        stubController.ControllerContext = controllerContext;
        return controllerContext;
    }

    string UrlRoot()
    {
        var httpContext = HttpContext.Current;
        if (httpContext == null)
        {
            return "http://localhost";
        }

        return httpContext.Request.Url.GetLeftPart(UriPartial.Authority) +
               httpContext.Request.ApplicationPath;
    }

如何指定UrlRoot,以便代替拉默认的localhost来根据我的子站点拉它?

How can I specify the UrlRoot so that instead of pulling the default of localhost to pull it based on my subsite?

推荐答案

下面是我认为比上面更优雅的另一种可能的解决方案.它还解决了在执行后台进程的同时访问MVC应用程序时出现的问题.

Below is another possible solution that I think is more elegant than above. It also resolves an issue that appears when accessing the MVC application while the background process is being executed.

public static void SendTypedEmailBackground()
{
    try
    {
        var engines = new ViewEngineCollection();
        var viewsPath = Path.GetFullPath(HostingEnvironment.MapPath(@"~/Views/Emails"));

        var eng = new FileSystemRazorViewEngine(viewsPath);
        engines.Add(eng);

        var email = new WebApplication1.Controllers.EmailController.TypedEmail();
        email.Date = DateTime.UtcNow.ToString();
        IEmailService service = new Postal.EmailService(engines);
        service.Send(email);

    }
    catch(Exception ex)
    {
        throw ex;
    }
}

这篇关于在子站点中使用邮政和Hangfire的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆