MVC无法找到局部视图

时间:2017-03-13 21:13:58

标签: asp.net asp.net-mvc controller asp.net-apicontroller

我有两个项目(AccountController和OrderController),一个是控制器,另一个是ApiController。控制器是AccountController,而OrderController是ApiController。

我需要从AccountController访问一个操作(发送帐户确认电子邮件,将视图转换为字符串)。这将在用户下订单时发生,当它检测到用户是新用户时,它会自动注册它,然后发出注册确认电子邮件(这是AccountController的责任。

以下是OrderController

的摘录
var context = new HttpContextWrapper(System.Web.HttpContext.Current);
var routeData = RouteTable.Routes.GetRouteData(context);
routeData.Values.Add("controller", "Account");
routeData.Values.Add("action", "Register");
var requestContext = new System.Web.Routing.RequestContext(context, routeData);
var controllerContext = new System.Web.Mvc.ControllerContext(requestContext, new AuthenticationController());
await AccountController.SendAddressRegistrationEmail(controllerContext,model);

这是AccountController上的部分,

public static async Task SendAddressRegistrationEmail(ControllerContext context, model)
{
    var manager = context.HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
    var helper = new UrlHelper(context.RequestContext);

    //// Generate the token and send it
    string encodedEmailToken = HttpUtility.UrlEncode(await manager.GenerateEmailConfirmationTokenAsync(model.ID));
    string body = ViewAsString(context, "~/Views/Templates/RegistrationConfirmation.cshtml", new RegistrationConfirmationMessage
    {
        EmailAddress = user.EmailAddress,
        Expiration = expiration,
        ConfirmationUrl = helper.Action("ConfirmEmail", "Account", new { userId = model.ID, encodedEmailToken = encodedEmailToken, ReturnUrl = returnUrl }, protocol: context.HttpContext.Request.Url.Scheme, hostName: context.HttpContext.Request.Url.Host)
    });

    await manager.SendEmailAsync(user.ID, "Confirm your account", body);
}

protected static string ViewAsString<T>(ControllerContext context, string viewName, T model)
{
    using (var sw = new StringWriter())
    {
        var viewResult = ViewEngines.Engines.FindPartialView(context, viewName);
        var viewContext = new ViewContext(context, viewResult.View, new ViewDataDictionary<T>(model), new TempDataDictionary(), sw);
        viewResult.View.Render(viewContext, sw);
        viewResult.ViewEngine.ReleaseView(context, viewResult.View);
        return sw.GetStringBuilder().ToString();
    }
}

FindPartialView始终返回NULL,部分视图位于(Views / Templates / RegistrationConfirmation.cshtml)。

当我确定控制器上下文是AccountController时,我是否遗漏了导致部分视图不可见的内容?或者“上下文”中有什么需要初始化?

0 个答案:

没有答案