Skip to content

Solved the problem with the System.Web.Razor couldn't be found. #4

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
103 changes: 97 additions & 6 deletions readme.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,97 @@
WebAPIContrib
=============

Community Contributions for ASP.NET Web API

http://webapicontrib.github.com/
WebApiContrib.Formatting.Razor
=============

A 'MediaTypeFormatter' for generating HTML markup for [ASP.NET Web API](http://asp.net/web-api) applications.

Overview

Before we dive into the details, here is a simple example of using the [`HtmlMediaTypeViewFormatter`](https://github.com/WebApiContrib/WebApiContrib.Formatting.Html/blob/master/src/WebApiContrib.Formatting.Html/Formatters/HtmlMediaTypeViewFormatter.cs) with Razor:

public class CustomerController : ApiController
{
public Customer Get()
{
return new Customer { Name = "John Doe", Country = "Country" };
}
}

This controller will simply return a Customer as JSON or XAML based on the "Accept" or "content-type" header.

By adding the HtmlMediaTypeViewFormatter to the global.asax and using the [`RazorViewLocator`](https://github.com/WebApiContrib/WebApiContrib.Formatting.Razor/blob/master/src/WebApiContrib.Formatting.Razor/RazorViewLocator.cs) and a [`RazorViewParser`](https://github.com/WebApiContrib/WebApiContrib.Formatting.Razor/blob/master/src/WebApiContrib.Formatting.Razor/RazorViewParser.cs) the code can also render the model as HTML by using a Razor view. By default the view will be located by convention, using the name of the returned model in this case "Customer.cshtml" or "Customer.vbhtml".

protected void Application_Start()
{
//...

GlobalConfiguration.Configuration.Formatters.Add(new HtmlMediaTypeViewFormatter());

GlobalViews.DefaultViewParser = new RazorViewParser();
GlobalViews.DefaultViewLocator = new RazorViewLocator();

//...
}

The [`GlobalViews`](https://github.com/WebApiContrib/WebApiContrib.Formatting.Html/blob/master/src/WebApiContrib.Formatting.Html/Configuration/GlobalViews.cs) and [`HtmlMediaTypeViewFormatter`](https://github.com/WebApiContrib/WebApiContrib.Formatting.Html/blob/master/src/WebApiContrib.Formatting.Html/Formatters/HtmlMediaTypeViewFormatter.cs) comes from the [WebApiContrib.Formatting.Html](https://github.com/WebApiContrib/WebApiContrib.Formatting.Html) project.

Views should be added to the web api projects ["~/Views"](https://github.com/WebApiContrib/WebApiContrib.Formatting.Razor/tree/master/samples/MvcWebApiSiteTest/Views) folder. Here is an example of a View:

<html>Hello @Model.Name! Welcome to Razor!</html>

2 Install packages

Get it from [NuGet](http://nuget.org/packages/WebApiContrib.Formatting.Razor):

Install-Package WebApiContrib.Formatting.Razor

3 How the View locator works

The razor view locator [`RazorViewLocator`](https://github.com/WebApiContrib/WebApiContrib.Formatting.Razor/blob/master/src/WebApiContrib.Formatting.Razor/RazorViewLocator.cs) vill try to locate a view by using either, convention, annotation, configuration or by returning a View. The views must be located in the follwoing folders:

~\Views
~\Views\Shared

The "~" is the root folder of the web application. Both .cshtml and .vbhtml are supported.

Note: There is no way to specify another paths at this moment, it's easy to implement a view locator. It's done by implementing the [`IViewLocator`](https://github.com/WebApiContrib/WebApiContrib.Formatting.Html/blob/master/src/WebApiContrib.Formatting.Html/Locators/IViewLocator.cs) interface located in the [WebApiContrib.Formatting.Html](https://github.com/WebApiContrib/WebApiContrib.Formatting.Html) assembly.

3.1 Using convention

By default the RazorViewLocator will locate a view by convention, it will try to find a view by the name of the model returned by the ApiController's methods. The following code will try to find a view with the name "Customer" in the "Views" or "Views\Shared" folder and use it to render the returnd

Customer model:


public class CustomerController : ApiController
{
public Customer Get()
{
return new Customer { Name = "John Doe", Country = "Country" };
}
}

To use the ApiController to render the Customer model with the Customer view, just use the following path in browser:

http://localhost/mysite/customer

3.2 Using annotation

A view could be specified for a specific mode by adding the [`ViewAttribute`](https://github.com/WebApiContrib/WebApiContrib.Formatting.Razor/blob/master/samples/MvcWebApiSiteTest/Controllers/HomeController.cs#L10) to the model returned by a ApiController method.


public class CustomerController : ApiController
{
public Customer Get()
{
return new Customer { Name = "John Doe", Country = "Country" };
}
}

[View("CustomerViaAttrib")]
public class Customer
{
public string Name { get; set; }

public string Country { get; set; }
}

This code will try to locate a view with the name "CustomerViaAttrib".
1,024 changes: 724 additions & 300 deletions samples/MvcWebApiSiteTest/Content/Site.css

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Web.Http;
using WebApiContrib.Formatting.Html;

namespace MvcWebApiSiteTest.Controllers
{
33 changes: 32 additions & 1 deletion samples/MvcWebApiSiteTest/Views/Customer.cshtml
Original file line number Diff line number Diff line change
@@ -1,6 +1,37 @@
@{
_Layout = "~/Views/Shared/_Layout.cshtml";
_Layout = "~/Views/Shared/_Layout.cshtml";
}
@section featured {
<section class="featured">
<div class="content-wrapper">

<div>
<hgroup class="title">
<h2>ASP.Net Web API using HtmlMediaTypeFormater and RazorEngine</h2>
</hgroup>
<p>
By using the HtmlMediaTypeViewFormatter and the Razor view parser, it's now possible to use ASP.Net Web API to render a model as HTML by using Razor.

This site will demonstrate the use of the formatter and the Razor parser.
</p>
</div>
</section>
}

@section contentMenu {
<li> <a href="#Quick_overview">Quick overview</a>
<ol><li> <a href="#Finding_a_Package">Finding a Package</a>
</li><li> <a href="#Package_Sources">Package Sources</a>
</li><li> <a href="#Installing_a_Package">Installing a Package</a>
</li><li> <a href="#Removing_a_Package">Removing a Package</a>
</li><li> <a href="#Updating_a_Package">Updating a Package</a>
</li></ol></li><li> <a href="#How_the_View_locator_works">How_the_View_locator_works</a>
<ol><li> <a href="#Using_convention">Using convention</a>
</li><li> <a href="#Using_configuration">Using configuration</a>
</li><li> <a href="#Updating_Packages">Updating Packages</a>
</li></ol></li>
}

<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.5.1.min.js" type="text/javascript"></script>
<div id="body">
6 changes: 5 additions & 1 deletion samples/MvcWebApiSiteTest/Views/CustomerViaAttrib.cshtml
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
<!DOCTYPE html>
@{
_Layout = "~/Views/Shared/_Layout.cshtml";
}

<!DOCTYPE html>
<html>

<head>
199 changes: 137 additions & 62 deletions samples/MvcWebApiSiteTest/Views/Index.cshtml
Original file line number Diff line number Diff line change
@@ -1,62 +1,137 @@

<!DOCTYPE html>
<html>

<head>
<meta charset='utf-8' />
<meta http-equiv="X-UA-Compatible" content="chrome=1" />
<meta name="description" content="WebApiContrib : Community Contributions for ASP.NET Web API" />

<link rel="stylesheet" type="text/css" media="screen" href="/Content/Site.css">

<title>WebApiContrib</title>
</head>

<body>

<!-- HEADER -->
<div id="header_wrap" class="outer">
<header class="inner">
<a id="forkme_banner" href="https://github.com/WebApiContrib/WebAPIContrib">Fork Me on GitHub</a>

<h1 id="project_title">WebApiContrib</h1>
<h2 id="project_tagline">Community Contributions for ASP.NET Web API</h2>

<section id="downloads">
<a class="zip_download_link" href="https://github.com/WebApiContrib/WebAPIContrib/zipball/master">Download this project as a .zip file</a>
<a class="tar_download_link" href="https://github.com/WebApiContrib/WebAPIContrib/tarball/master">Download this project as a tar.gz file</a>
</section>
</header>
</div>

<!-- MAIN CONTENT -->
<div id="main_content_wrap" class="outer">
<section id="main_content" class="inner">
<h3>WebApiContrib</h3>

<p>WebApiContrib is a collection of projects and samples built by the community for to enhance and improve the <a href="http://www.asp.net/web-api">ASP.NET Web API framework.</a></p>

<p>More information will be coming very soon!</p>
</section>
</div>

<!-- FOOTER -->
<div id="footer_wrap" class="outer">
<footer class="inner">
<p class="copyright">WebApiContrib maintained by <a href="https://github.com/WebApiContrib">WebApiContrib</a></p>
<p>Published with <a href="http://pages.github.com">GitHub Pages</a></p>
</footer>
</div>

<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-30452127-1']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</body>
</html>
@{
_Layout = "~/Views/Shared/_Layout.cshtml";
}

@section featured {
<section class="featured">
<div class="content-wrapper">

<div>
<hgroup class="title">
<h2>ASP.Net Web API using HtmlMediaTypeFormater and RazorEngine</h2>
</hgroup>
<p>
By using the HtmlMediaTypeViewFormatter and the Razor view parser, it's now possible to use ASP.Net Web API to render a model as HTML by using Razor.

This site will demonstrate the use of the formatter and the Razor parser.
</p>
</div>
</section>
}

@section contentMenu {
<li> <a href="#Quick_overview">Quick overview</a></li>
<li> <a href="#Install_packages">Install Packages</a></li>
<li> <a href="#How_the_View_locator_works">How the View locator works</a>
<ol><li> <a href="#Using_convention">Using convention</a>
</li><li> <a href="#Using_configuration">Using annotation</a>
</li><li> <a href="#Using_convention">Using configuration</a>
</li></ol></li>
}


<h3 id="Quick_overview">1 Quick overview</h3>

<p>Before we dive into the details, here is a simple example of using the HtmlMediaTypeViewFormatter with Razor:</p>
<pre class="cs">
<code>
public class CustomerController : ApiController
{
public Customer Get()
{
return new Customer { Name = "John Doe", Country = "Country" };
}
}
</code>
</pre>
<p>
This controller will simply return a Customer as JSON or XAML based on the "Accept" or "content-type" header.
</p>
<p>
By adding the HtmlMediaTypeViewFormatter to the global.asax and using the RazorViewLocator and a RazorViewParser the code can also render the model as HTML by using a View. By deafult the view tried to be located
is "Customer.cshtml" or "Customer.vbhtml", based on the name of the model returned.
</p>
<pre class="cs">
<code>
protected void Application_Start()
{
//...
GlobalConfiguration.Configuration.Formatters.Add(new HtmlMediaTypeViewFormatter());

GlobalViews.DefaultViewParser = new RazorViewParser();
GlobalViews.DefaultViewLocator = new RazorViewLocator();

//...
}
</code>
</pre>
<p>
Customer.cshtml located in the "~/Views" folder of the web project
</p>
<pre class="html">
<code>
&lt;html&gt;Hello &#64;Model.Name! Welcome to Razor!&lt;/html&gt;
</code>
</pre>

<h3 id="Install_packages">2 Install packages</h3>
<p>To be updated....</p>

<h3 id="How_the_View_locator_works">3 How the View locator works</h3>
<p>
The razor view locator (RazorViewLocator) vill try to locate a view by using either, convention, annotation, configuration or by returning a View.
The views must be located in the follwoing folders:<pre>
<code>
~\Views
~\Views\Shared
</code></pre>
<p>
The "~" is the root folder of the web application. Both .cshtml and .vbhtml are supported.
</p>
<p>
<i>Note: There is no way to specify another paths at this moment, it's easy to implement a view locator. It's done by implementing the IViewLocator interface located in the WebApiContrib.Formatting.Html assembly.</i>
</p>

<h3 id="Using_convention">3.1 Using convention</h3>
<p>
By default the RazorViewLocator will locate a view by convention, it will try to find a view by the name of the model returned by the ApiController's methods.
The following code will try to find a view with the name "Customer" in the "Views" or "Views\Shared" folder and use it to render the returnd Customer model:
<pre class="C#"><code>
public class CustomerController : ApiController
{
public Customer Get()
{
return new Customer { Name = "John Doe", Country = "Country" };
}
}
</code></pre>
To use the ApiController to render the Customer model with the Customer view, just use the following path in browser:</p>
<p>
<a href="/Customer">http://localhost/mysite/customer</a>
</p>

<h3 id="Using_annotation">3.2 Using annotation</h3>
<p>
A view could be specified for a specific mode by adding the ViewAttribute to the model returned by a ApiController method.
</p>
<pre class="c#"><code>
public class CustomerController : ApiController
{
public Customer Get()
{
return new Customer { Name = "John Doe", Country = "Country" };
}
}

[View("CustomerViaAttrib")]
public class Customer
{
public string Name { get; set; }

public string Country { get; set; }
}
</code></pre>
<p>
This code will try to locate a view with the name "CustomerViaAttrib".
</p>
78 changes: 68 additions & 10 deletions samples/MvcWebApiSiteTest/Views/Shared/_Layout.cshtml
Original file line number Diff line number Diff line change
@@ -1,10 +1,68 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
</head>
<body>
@RenderBody()
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>ASP.Net Web API - Razor</title>
<link href="/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width" />
<link href="/Content/Site.css" rel="stylesheet" />
</head>
<body>
<header>
<div class="content-wrapper">
<div class="float-left">
<p class="site-title">ASP.Net Web API - Razor</p>
</div>
<div class="float-right">
<nav>
<ul id="menu">
<li>Home</li>
<li>About</li>
<li>Contact</li>
</ul>
</nav>
</div>
</div>
</header>
<div id="body">

<section class="featured">
@RenderSection("featured")
</section>

<section class="content-wrapper main-content clear-fix">

<aside id="toc">
<div id="toc-main">
<h3 id="toc-heading">Content</h3>
<ol id="toc-body">
@RenderSection("contentMenu")
</ol>
</div>
</aside>

@RenderBody()

</section>

</div>
<footer>
<div class="content-wrapper">
<div class="float-left">
<p>&copy; @DateTime.Now.Year - .Net Guides</p>
</div>
<div class="float-right">
<ul id="social">
<li><a href="http://facebook.com" class="facebook">Facebook</a></li>
<li><a href="http://twitter.com" class="twitter">Twitter</a></li>
</ul>
</div>
</div>
</footer>

<link rel="stylesheet" href="http://yandex.st/highlightjs/7.0/styles/default.min.css">
<script src="http://yandex.st/highlightjs/7.0/highlight.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>

</body>
</html>
188 changes: 94 additions & 94 deletions samples/MvcWebApiSiteTest/Web.config
Original file line number Diff line number Diff line change
@@ -1,95 +1,95 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-MvcWebApiSiteTest-20120821092832;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-MvcWebApiSiteTest-20120821092832.mdf" />
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="2.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="PreserveLoginUrl" value="true" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<authentication mode="None" />
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Optimization" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
</namespaces>
</pages>
<profile defaultProvider="DefaultProfileProvider">
<providers>
<add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
</providers>
</profile>
<membership defaultProvider="DefaultMembershipProvider">
<providers>
<add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
<roleManager defaultProvider="DefaultRoleProvider">
<providers>
<add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
</providers>
</roleManager>
<sessionState mode="InProc" customProvider="DefaultSessionProvider">
<providers>
<add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />
</providers>
</sessionState>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true" />
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Razor" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-MvcWebApiSiteTest-20120821092832;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-MvcWebApiSiteTest-20120821092832.mdf" />
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="2.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="PreserveLoginUrl" value="true" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<authentication mode="None" />
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Optimization" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
</namespaces>
</pages>
<profile defaultProvider="DefaultProfileProvider">
<providers>
<add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
</providers>
</profile>
<membership defaultProvider="DefaultMembershipProvider">
<providers>
<add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
<roleManager defaultProvider="DefaultRoleProvider">
<providers>
<add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
</providers>
</roleManager>
<sessionState mode="InProc" customProvider="DefaultSessionProvider">
<providers>
<add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />
</providers>
</sessionState>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true" />
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
<!--<dependentAssembly>
<assemblyIdentity name="System.Web.Razor" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>-->
</assemblyBinding>
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>
50 changes: 39 additions & 11 deletions src/WebApiContrib.Formatting.Razor/RazorViewParser.cs
Original file line number Diff line number Diff line change
@@ -9,22 +9,24 @@ namespace WebApiContrib.Formatting.Razor
{
public class RazorViewParser : IViewParser
{
private readonly ITemplateService _templateService;
private ITemplateService _templateService;

public RazorViewParser(ITemplateService templateService)

public RazorViewParser()
{
//var config = new TemplateServiceConfiguration { Resolver = new TemplateResolver() };
//_templateService = new TemplateService(config);
}


public RazorViewParser(ITemplateService templateService)
{
if (templateService == null)
throw new ArgumentNullException("templateService");

_templateService = templateService;
}

public RazorViewParser()
{
var config = new TemplateServiceConfiguration { Resolver = new TemplateResolver() };
_templateService = new TemplateService(config);
}


public RazorViewParser(ITemplateResolver resolver)
{
@@ -45,14 +47,40 @@ public byte[] ParseView(IView view, string viewTemplate, System.Text.Encoding en

private string GetParsedView(IView view, string viewTemplate)
{
var implicitSetWorkaround = false;

// 1* THIS IF STATEMENT IS ONLY ADDED AS A TEMPORARY WORKAROUND
// There is probably a bug in the RazorEngine when trying to set the Model property of a template
// next time this code runs.
// A new instance need to be created, I think it has to do with a cache the TemplateService uses.
if (_templateService == null)
{
var config = new TemplateServiceConfiguration {Resolver = new TemplateResolver()};
_templateService = new TemplateService(config);

implicitSetWorkaround = true;
}



string result = string.Empty;

if (view.ModelType == null)
{
_templateService.Compile(viewTemplate, view.ViewName);
return _templateService.Run(view.ViewName);
result = _templateService.Run(view.ViewName);
}
else
{
_templateService.Compile(viewTemplate, view.ModelType, view.ViewName);
result = _templateService.Run(view.ViewName, view.Model);
}

// Workaround to solve a bug, see comment 1* above.
if (implicitSetWorkaround)
_templateService = null;

_templateService.Compile(viewTemplate, view.ModelType, view.ViewName);
return _templateService.Run(view.ViewName, view.Model);
return result;
}
}
}