从linqpad或控制台应用程序运行asp.net mvc应用程序
问题描述:
如何从我的mvc应用程序的某些操作启动并获取ActionResult仅使用Linqpad或控制台应用程序?从linqpad或控制台应用程序运行asp.net mvc应用程序
我知道我可以创建MvcApplication类instanse:
var mvcApplication = new Web.MvcApplication();
然后创建控制器:
var homeController = new Web.Controllers.HomeController();
即使运行控制器的动作
homeController.Index()
但它没有返回。什么是mvc应用程序的生命周期?我应该调用哪些方法模拟用户的Web请求?
编辑
这里关于ASP.NET MVC生命周期的一些好职位,但unfortunally我解决不了我的问题还没有
http://blog.stevensanderson.com/2007/11/20/aspnet-mvc-pipeline-lifecycle/
答
我知道这是一个老问题,并可能在别处得到解答,但在我正在开发的一个项目中,我们可以使用Linqpad调试Controller Actions d得到返回的值。
简单地说,你需要告诉Linqpad返回的东西:
var result = homeController.Index();
result.Dump();
您可能还需要模拟你的背景和附加视觉工作室的调试器。
完整的代码片段:
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 "[email protected]";} }
}
你应该得到提示选择一个调试器,与您的应用程序选择内置的Visual Studio的实例。
我们针对MVC-CRM进行了具体设置,因此这可能不适用于所有人,但希望这可以帮助其他人。
我可以问一下这样一个专长的目标是什么吗? – 2013-03-18 14:03:19
@Kenneth K主要目的是使测试和错误修复更容易。当然,我可以使用单元测试,但他们并没有像Linqpad中的转储那样强大的输出方法。 – Neir0 2013-03-18 14:06:51
@Kenneth K另一个原因是更好地理解asp.net mvc应用程序的实际工作方式。当你试图用自己的手做时,阅读任何文章都会好得多。 – Neir0 2013-03-18 14:13:11