【问题标题】:Run asp.net mvc application from linqpad or console application从 linqpad 或控制台应用程序运行 asp.net mvc 应用程序
【发布时间】:2013-03-18 13:26:38
【问题描述】:

如何从我的 mvc 应用程序的某些操作中启动和获取 ActionResult,仅使用 Linqpad 或控制台应用程序?

我知道我可以创建 MvcApplication 类实例:

var mvcApplication = new Web.MvcApplication();

然后创建控制器:

var homeController = new Web.Controllers.HomeController();

甚至运行控制器的操作

homeController.Index()

但它什么也不返回。 mvc 应用程序的生命周期是什么?我应该调用哪些方法来模拟来自用户的 Web 请求?

编辑


这里有一些关于 ASP.NET MVC 生命周期的好帖子,但不幸的是我还不能解决我的问题

http://stephenwalther.com/archive/2008/03/18/asp-net-mvc-in-depth-the-life-of-an-asp-net-mvc-request.aspx

http://blog.stevensanderson.com/2007/11/20/aspnet-mvc-pipeline-lifecycle/

【问题讨论】:

  • 我可以问一下这样一个壮举的目标是什么?
  • @Kenneth K 主要目的是让测试和错误修复更容易。当然我可以使用单元测试,但他们没有像 Linqpad 中的 Dump 这样强大的输出方法。
  • @Kenneth K 另一个原因是更好地了解 asp.net mvc 应用程序的实际工作原理。当您尝试自己动手做时,比阅读任何文章要好得多。
  • 我只是确认您不想查看原始请求/响应,您可以使用 Fiddler 来做这些事情。听起来你想要更深入一点:)
  • @Kenneth K. 谢谢,我知道 Fiddler,但我的问题在另一方面 :)

标签: c# asp.net-mvc linqpad


【解决方案1】:

我知道这是一个老问题,可能会在其他地方得到回答,但在我正在处理的项目中,我们可以使用 Linqpad 调试控制器操作并获取返回值。

简单地说,你需要告诉 Linqpad 返回一些东西:

var result = homeController.Index();
result.Dump();

您可能还需要模拟您的上下文并将 Visual Studio 附加为调试器。

完整代码sn-p:

void Main()
{       
    using(var svc = new  CrmOrganizationServiceContext(new CrmConnection("Xrm"))) 
    {
        DummyIdentity User = new DummyIdentity();

        using (var context = new XrmDataContext(svc)) 
        {
            // Attach the Visual Studio debugger
            System.Diagnostics.Debugger.Launch();
            // Instantiate the Controller to be tested
            var controller = new HomeController(svc);
            // Instantiate the Context, this is needed for IPrincipal User
            var controllerContext = new ControllerContext(); 

            controllerContext.HttpContext = new DummyHttpContext();
            controller.ControllerContext = controllerContext; 

            // Test the action
            var result = controller.Index();
            result.Dump();
        }
    }             
}

// Below is the Mocking classes used to sub in Context, User, etc.
public class DummyHttpContext:HttpContextBase {
    public override IPrincipal User {get {return new  DummyPrincipal();}}
}

public class DummyPrincipal : IPrincipal 
{
    public bool IsInRole(string role) {return role == "User";} 
    public IIdentity Identity {get {return new DummyIdentity();}}
}

public class DummyIdentity : IIdentity 
{
    public string AuthenticationType { get {return "?";} }
    public bool IsAuthenticated { get {return true;}}
    public string Name { get {return "sampleuser@email.com";} }
}

应该会提示您选择调试器,选择构建您的应用的 Visual Studio 实例。

我们有一个针对 MVC-CRM 的特定设置,所以这可能并不适合所有人,但希望这会帮助其他人。

【讨论】:

    猜你喜欢
    • 2018-11-21
    • 2011-01-22
    • 1970-01-01
    • 2018-05-14
    • 1970-01-01
    • 1970-01-01
    • 2014-01-24
    • 1970-01-01
    • 2019-02-10
    相关资源
    最近更新 更多