最近在研究Razor和MVC,打算逐步把博客用Razor重写一边。今天一上手就碰到个蛋碎的问题。不管是在MVC应用程序,还是传统的WebForm项目中添加Razor页(既.cshtml类型的页面),就会导致自定义的Membership Provider失效。如果去掉Membership的配置则一切正常。

具体问题表现在有两个地方报错:

1. 运行时报错:
Parser Error Message: Default Membership Provider could not be found.

2. 编译时报错:
Error    58    The pre-application start initialization method Start on type System.Web.WebPages.Deployment.PreApplicationStartCode threw an exception with the following error message: Exception has been thrown by the target of an invocation..

我蛋疼了半天,发现这和web.config有关。添加razor页面的时候,VS会自动在web.config里加一句:

<add key="webpages:Enabled" value="true" />

如果把这句话去掉,网站就能编译通过。但cshtml会不能显示,传统aspx页面还是可以运行的。但我们的目的毕竟还是要用razor,肿么办呢?

经过一番非常蛋疼的搜索和实验,终于找到了解决办法:在Web.config中的appSettings节点加入下面的配置。

<add key="enableSimpleMembership" value="false" />
<add key="autoFormsAuthentication" value="false" />

现在,aspx和cshtml都能运行,并且不会和自定义的MembershipProvider冲突。