Web Api控制器可以将视图呈现为字符串吗?

时间:2016-03-22 17:33:57

标签: asp.net-web-api

我想编写一个Web Api控制器操作,根据结果发送电子邮件。我想使用带有数据模型的MVC视图或部分视图来呈现电子邮件的正文。

有办法做到这一点吗?

我想要这样的事情:

public class NotificationApiController : ApiController
{
    private IMkpContext db;

    public string ViewNotifications()
    {
        var dataModel = GetDataModel();
        if (dataModel != null) 
        {
            SendEmail(dataModel.ToAddress, dataModel.FromAddress, dataModel.Subject, RenderBody("viewName", dataModel);
        }

        return string.Empty;
    }
}

RenderBody将查找viewName,使用dataModel中的数据填充它,并将View渲染为字符串。

1 个答案:

答案 0 :(得分:2)

如果你不想使用评论中建议的RazorEngine方法,你可以定义一个这样的类:

public static class ViewUtil
{
    public static string RenderPartial(string partialName, object model)
    {
        var sw = new StringWriter();
        var httpContext = new HttpContextWrapper(HttpContext.Current);

        // point to an empty controller
        var routeData = new RouteData();
        routeData.Values.Add("controller", "EmptyController");

        var controllerContext = new ControllerContext(new RequestContext(httpContext, routeData), new EmptyController());

        var view = ViewEngines.Engines.FindPartialView(controllerContext, partialName).View;

        view.Render(new ViewContext(controllerContext, view, new ViewDataDictionary { Model = model }, new TempDataDictionary(), sw), sw);

        return sw.ToString();
    }
}

class EmptyController : Controller { }