Workaround in ASP.Net WebApi Help Page

The Nuget package Microsoft.AspNet.WebApi.HelpPage is really helpful to automatically create the needed help for your web API. But sometimes, depending on your solution structure, it can be difficult to use it.

The package works really fine, smooth and unassisted when you have the standard MVC template in your web API project, but what happen if we complicate it a bit? For instance, in a bigger solution, we might want to split the models in an independent project and, besides, we have the same name of a class but in a different namespace. Personally I prefer to have different name of classes for different purposes, even if they are in different namespaces, but, sometimes, you need to choose between adding prefixes of suffixes to the classes names, or having the same name.

Let's make a small test. First of all, we create an MVC application with a WebAPI (or simply a Web API application, it does not matter for this article but I decided to start with this template to show how to add a Help Page from scratch).

new project

mvc template

If we run the application we can see the standard base application executing. Let's add to that application, a new ApiController with a model.

add api controller

And let's name this controller “MoneyBanksController”. The template that will be created will be similar to this one.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7.   
  8. namespace HelpPageErrorSimulator.Controllers  
  9. {  
  10.     public class MoneyBanksController : ApiController  
  11.     {  
  12.         // GET: api/MoneyBanks  
  13.         public IEnumerable<string> Get()  
  14.         {  
  15.             return new string[] { "value1""value2" };  
  16.         }  
  17.   
  18.         // GET: api/MoneyBanks/5  
  19.         public string Get(int id)  
  20.         {  
  21.             return "value";  
  22.         }  
  23.   
  24.         // POST: api/MoneyBanks  
  25.         public void Post([FromBody]string value)  
  26.         {  
  27.         }  
  28.   
  29.         // PUT: api/MoneyBanks/5  
  30.         public void Put(int id, [FromBody]string value)  
  31.         {  
  32.         }  
  33.   
  34.         // DELETE: api/MoneyBanks/5  
  35.         public void Delete(int id)  
  36.         {  
  37.         }  
  38.     }  

Now, let's change the template “string” type by a new class named “Bank”. The result will be something like this.

  1. {  
  2.     // GET: api/MoneyBanks  
  3.     public IEnumerable<Bank> Get()  
  4.     {  
  5.         return new Bank[] { new Bank(), new Bank() };  
  6.     }  
  7.   
  8.     // GET: api/MoneyBanks/5  
  9.     public string Get(int id)  
  10.     {  
  11.         return "value";  
  12.     }  
  13.   
  14.     // POST: api/MoneyBanks  
  15.     public void Post([FromBody]Bank value)  
  16.     {  
  17.     }  
  18.   
  19.     // PUT: api/MoneyBanks/5  
  20.     public void Put(int id, [FromBody]Bank value)  
  21.     {  
  22.     }  
  23.   
  24.     // DELETE: api/MoneyBanks/5  
  25.     public void Delete(int id)  
  26.     {  
  27.     }  

Of course, since we didn't write the Bank class yet, it appears in Red. Let's create the class inside the Models folder.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace HelpPageErrorSimulator.Models  
  7. {  
  8.     public class Bank  
  9.     {  
  10.         public string Name { getset; }  
  11.         public string Special1 { getset; }  
  12.         public string Special2 { getset; }  
  13.     }  

Now we can go back to the MoneyBanks controller and add a reference to the namespace containing the Bank class.

  1. using HelpPageErrorSimulator.Models; 

Now we can add the HelpPages Nuget package. To do that, open the Package Manager Console and write this command.

PM> install-package Microsoft.AspNet.WebApi.HelpPage

If we run the application now, we are able to navigate to the URL “/help” and we will see the help page for the controller we wrote. Pretty simple, huh?

url help

Let's complicate the system a bit. In a big application, you should have your models in an external project. That way, if you have a N-layer architecture, you can use the models everywhere. So, let's do it. We create a new project in the solution of the class “Windows Desktop/Class lIbrary” and we call it MoneyBanks.Models.

Then, we can delete the created class in the new project and cut and paste our Bank class to this project. The only thing we need to do is to fix the namespace name in the class. It should end like this.

  1. namespace MoneyBanks.Models  
  2. {  
  3.     public class Bank  
  4.     {  
  5.         public string Name { getset; }  
  6.         public string Special1 { getset; }  
  7.         public string Special2 { getset; }  
  8.     }  

Of course, now we need to reference this new project from the web application and then, add a reference to that namespace in the MoneyBanks ApiController:

  1. using MoneyBanks.Models; 

If we run the application now, we won't see any difference with the all-in-one template application we had before.

Now we will force a problem.

Let's say, our application is about banks, but about different types of banks, we already created the webapi for the money banks and now we want to create a new webapi for blood banks.

Let's start adding a controller for that. As we did previously, no difference but the name used. This time, we will call this controller “BloodBanksController”.

Let's change the class used in this controller. If you compare this controller with the other one, they look the same.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7.   
  8. namespace HelpPageErrorSimulator.Controllers  
  9. {  
  10.     public class BloodBanksController : ApiController  
  11.     {  
  12.         // GET: api/BloodBanks  
  13.         public IEnumerable<Bank> Get()  
  14.         {  
  15.             return new Bank[] { new Bank(), new Bank() };  
  16.         }  
  17.   
  18.         // GET: api/BloodBanks/5  
  19.         public string Get(int id)  
  20.         {  
  21.             return "value";  
  22.         }  
  23.   
  24.         // POST: api/BloodBanks  
  25.         public void Post([FromBody]Bank value)  
  26.         {  
  27.         }  
  28.   
  29.         // PUT: api/BloodBanks/5  
  30.         public void Put(int id, [FromBody]Bank value)  
  31.         {  
  32.         }  
  33.   
  34.         // DELETE: api/BloodBanks/5  
  35.         public void Delete(int id)  
  36.         {  
  37.         }  
  38.     }  

As before, we have in Red the nonexisting class, so, let's create it. To do that, we will create a new class library project called BloodBanks.Models. Then, we changed the automatically created class1.cs by this code.

  1. namespace BloodBanks.Models  
  2. {  
  3.     public class Bank  
  4.     {  
  5.         public string Name { getset; }  
  6.         public string Special3 { getset; }  
  7.         public string Special4 { getset; }  
  8.     }  

As you can see, the only difference with the “other” Bank class, is the namespace and a couple of properties with a different name. Now we can go back to the controller project, add a reference to this new project and add a new using class to the controller.

  1. using System.Collections.Generic;  
  2. using System.Web.Http;  
  3. using BloodBanks.Models;  
  4.   
  5. namespace HelpPageErrorSimulator.Controllers  
  6. {  
  7.     public class BloodBanksController : ApiController  
  8.     {  
  9.         // GET: api/BloodBanks  
  10.         public IEnumerable<Bank> Get()  
  11.         {  
  12.             return new Bank[] { new Bank(), new Bank() };  
  13.         }  
  14.   
  15.         // GET: api/BloodBanks/5  
  16.         public string Get(int id)  
  17.         {  
  18.             return "value";  
  19.         }  
  20.   
  21.         // POST: api/BloodBanks  
  22.         public void Post([FromBody]Bank value)  
  23.         {  
  24.         }  
  25.   
  26.         // PUT: api/BloodBanks/5  
  27.         public void Put(int id, [FromBody]Bank value)  
  28.         {  
  29.         }  
  30.   
  31.         // DELETE: api/BloodBanks/5  
  32.         public void Delete(int id)  
  33.         {  
  34.         }  
  35.     }  

Now run the application in the help page.

run app

Everything seems to be working fine, right? Well, click on any method and it should raise an exception (A model description could not be created. Duplicate model name 'Bank' was found for types 'MoneyBanks.Models.Bank' and 'BloodBanks.Models.Bank'. Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.).

The problem is that the help page creator is finding a collision between the two classes that have the same name.

server error

The Solutions

First solution

What the error is telling you, is that you need to use the [ModelName] attribute in at least one of the classes, naming it differently to avoid the collision. Well, we can do it in our solution, but it won't work. Let's try, let's modify, for instance, the first Bank class to add that attribute.

  1. namespace MoneyBanks.Models  
  2. {  
  3.     [ModelName("MoneyBank")]  
  4.     public class Bank  
  5.     {  
  6.         public string Name { getset; }  
  7.         public string Special1 { getset; }  
  8.         public string Special2 { getset; }  
  9.     }  

Well, it will never find the ModelName attribute, because it's implementation is inside the web application project, inside the help area, so, if we reference that project, it will cause a circular reference problem.

We can avoid it by creating a new project in the solution. The target of this new project is to have the help pages module inside.

So, let's create a new class library project called HelpPageErrorSimulator.HelpArea. Once it is created, let's make some surgery to the Web project and the new project:

  • Create a folder in the HelpPageErrorSimulator.HelpArea called Areas.

  • Create a folder in the HelpPageErrorSimulator.HelpArea, inside the Areas folder, called HelpPage.

  • Move everything in the Web project under the folder Areas/HelpPage to the recent created folder of the secondary project, EXCEPT the Views folder and the HelpPage.css file.
If we try to build the solution now, we will see that obviously we need to add some references to the new project, those are:
  • System.ComponentModel.DataAnnotations
  • System.Runtime.Serialization
  • System.Web
  • System.Web.Helpers
  • System.Web.Http
  • System.Net
  • System.Net.Http
  • System.Net.Http.Formatting

Then, we need to add these packages to the new project, as we did before, using the Package Manager Console:

  • Install-Package Microsoft.AspNet.Mvc -Version 5.2.3
  • Install-Package Microsoft.AspNet.WebApi.Client
  • Install-Package Microsoft.AspNet.WebApi.Core
  • Install-Package Newtonsoft.Json -Version 6.0.8
  • Install-Package Microsoft.AspNet.WebApi.WebHost -version 5.2.3

After adding all these references, we will be able to build the new project. Now, to have all working, we need to add a reference to this new project in our web application and a reference to this new project to the MoneyBanks.Models project.

Then, edit the MoneyBanks.Models.Bank class and add a using clause, it will end like this.

  1. using HelpPageErrorSimulator.Areas.HelpPage.ModelDescriptions;  
  2.   
  3. namespace MoneyBanks.Models  
  4. {  
  5.     [ModelName("MoneyBank")]  
  6.     public class Bank  
  7.     {  
  8.         public string Name { getset; }  
  9.         public string Special1 { getset; }  
  10.         public string Special2 { getset; }  
  11.     }  

As you can see, the ModelName attribute is not in Red, so, we have done things well.

It's time to run the application again.

If you click on the first method link of the MoneyBank API, now you can see that the help is working and it shows you a link to your “Named” model MoneyBank, instead of the real name of the class.

You can see the full project from GitHub here.

Second solution

What the error is telling you, is that you need to use the [ModelName] attribute in, at least, one of the classes, naming it differently to avoid the collision. If you do it, as we show in the first solution, you will see a different name of the Bank class in your help. It might not be what you want, since the name of the class may be important. I think that the best solution is to add to the help system the entire namespace of the class. That way, we don't have the same name in different classes and, then, we avoid the problem.

Also, with this solution, we don't need to add the ModelName attribute to any class.

To do it, we need to change some classes in the original help system to use, instead of the name of the class, the FULLNAME of the class that has the complete namespace.

We need to change this classes:

  • ModelNameHelper
  • HelpPageSampleGenerator

Replace, in ModelNameHelper, the content of the class with this.

  1. using System;  
  2. using System.Globalization;  
  3. using System.Linq;  
  4. using System.Reflection;  
  5.   
  6. namespace HelpPageErrorSimulator.Areas.HelpPage.ModelDescriptions  
  7. {  
  8.     internal static class ModelNameHelper  
  9.     {  
  10.         // Modify this to provide custom model name mapping.  
  11.         public static string GetModelName(Type type)  
  12.         {  
  13.             ModelNameAttribute modelNameAttribute = type.GetCustomAttribute<ModelNameAttribute>();  
  14.             if (modelNameAttribute != null && !String.IsNullOrEmpty(modelNameAttribute.Name))  
  15.             {  
  16.                 return modelNameAttribute.Name;  
  17.             }  
  18.   
  19.             string modelName = type.FullName;  
  20.             if (type.IsGenericType)  
  21.             {  
  22.                 // Format the generic type name to something like: GenericOfAgurment1AndArgument2  
  23.                 Type genericType = type.GetGenericTypeDefinition();  
  24.                 Type[] genericArguments = type.GetGenericArguments();  
  25.                 string genericTypeName = genericType.FullName;  
  26.   
  27.                 // Trim the generic parameter counts from the name  
  28.                 genericTypeName = genericTypeName.Substring(0, genericTypeName.IndexOf('`'));  
  29.                 string[] argumentTypeNames = genericArguments.Select(t => GetModelName(t)).ToArray();  
  30.                 modelName = String.Format(CultureInfo.InvariantCulture, "{0}Of{1}", genericTypeName, String.Join("And", argumentTypeNames));  
  31.             }  
  32.   
  33.             return modelName;  
  34.         }  
  35.     }  

As you can see, if you compare the changes I've made, they are simple. I changed the type.Name by type.FullName and genericType.Name by genericType.FullName (not really necessary this last one).

This way, instead of getting the name of the class, the system will get the full name, including the namespace.

Replace, in HelpPageSampleGenerator, the method WriteSampleObjectUsingFormatter with this one.

  1. [SuppressMessage("Microsoft.Design""CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]  
  2. public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)  
  3. {  
  4.     if (formatter == null)  
  5.     {  
  6.         throw new ArgumentNullException("formatter");  
  7.     }  
  8.     if (mediaType == null)  
  9.     {  
  10.         throw new ArgumentNullException("mediaType");  
  11.     }  
  12.   
  13.     object sample = String.Empty;  
  14.     MemoryStream ms = null;  
  15.     HttpContent content = null;  
  16.     try  
  17.     {  
  18.         if (formatter.CanWriteType(type))  
  19.         {  
  20.             ms = new MemoryStream();  
  21.             content = new ObjectContent(type, value, formatter, mediaType);  
  22.             formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();  
  23.             ms.Position = 0;  
  24.             StreamReader reader = new StreamReader(ms);  
  25.             string serializedSampleString = reader.ReadToEnd();  
  26.             if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))  
  27.             {  
  28.                 serializedSampleString = TryFormatXml(serializedSampleString);  
  29.             }  
  30.             else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))  
  31.             {  
  32.                 serializedSampleString = TryFormatJson(serializedSampleString);  
  33.             }  
  34.   
  35.             sample = new TextSample(serializedSampleString);  
  36.         }  
  37.         else  
  38.         {  
  39.             sample = new InvalidSample(String.Format(  
  40.                 CultureInfo.CurrentCulture,  
  41.                 "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",  
  42.                 mediaType,  
  43.                 formatter.GetType().FullName,  
  44.                 type.FullName));  
  45.         }  
  46.     }  
  47.     catch (Exception e)  
  48.     {  
  49.         sample = new InvalidSample(String.Format(  
  50.             CultureInfo.CurrentCulture,  
  51.             "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",  
  52.             formatter.GetType().FullName,  
  53.             mediaType.MediaType,  
  54.             UnwrapException(e).Message));  
  55.     }  
  56.     finally  
  57.     {  
  58.         if (ms != null)  
  59.         {  
  60.             ms.Dispose();  
  61.         }  
  62.         if (content != null)  
  63.         {  
  64.             content.Dispose();  
  65.         }  
  66.     }  
  67.   
  68.     return sample;  

If you take a look at the code, I have done exactly the same here, instead of formatter.GetType().Name, I've written formatter.GetType().FullName and instead of type.Name I've written type.FullName.

After doing that, you can run the application showing the help page and, if you click on a link, you will see, instead of the name of the class, the full namespace of the class.

moneybanks

And that is everything. Now the help system will work even with classes with the same name in various namespaces.

You can see the full project from GitHub.

I hope this helps you in your projects.

You can see more articles like this.

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now