Adding a simple Test Client to ASP.NET Web API Help Page


ASP.NET Web API Help Page is a useful extension that automatically generates a web-based documentation for you Web APIs. It makes debugging easier because you can copy/paste the information from Help Page to tools like Fiddler, to call your Web API service and examine the response.

Now, wouldn’t it be cool if you can do this directly on the Help Page without even leaving the browser? Well, now you can, with the Web API Test Client package. Note that it’s not an official package released by Microsoft. It’s just a simple prototype that I put together on my spare time.

Getting started

Step 1: Install the Test Client package

Install the WebApiTestClient package from the NuGet Package Manager. Make sure to “Include Prerelease” then just type in “WebApiTestClient” and click Install.

image

Once the package is installed, it will add the following files to your project:

  • Scripts\WebApiTestClient.js
  • Areas\HelpPage\TestClient.css
  • Areas\HelpPage\Views\Help\DisplayTemplates\TestClientDialogs.cshtml
  • Areas\HelpPage\Views\Help\DisplayTemplates\TestClientReferences.cshtml

It will also pull in the ASP.NET Web API Help Page package if it’s not already installed.

Step 2: Wire up the Test Client on Help Page

Open the file Api.cshtml (under Areas\HelpPage\Views\Help) and add the following:

  • @Html.DisplayForModel("TestClientDialogs")
  • @Html.DisplayForModel("TestClientReferences")

Note that you add the @Html.DisplayForModel("TestClientDialogs") after the <div> and @Html.DisplayForModel("TestClientReferences") inside the Scripts section.

image

You need to have the following JavaScript libraries installed. They should be installed if you used the default Web API template. Now, if you have different version numbers, you can update the references in TestClientReferences.cshtml.

  • jQuery 1.7.1
  • jQuery.UI.Combined 1.8.20
  • knockoutjs 2.1.0

Once everything is wired up correctly, you should see the “Test API” button appearing on the bottom right corner of the API page.

image

 

Testing Web APIs

Now you can click on the “Test API” button to start testing the APIs. For each URI parameters, it will automatically provide a text box so that you can fill in the value instead of editing the URI. Note that the URI automatically gets updated as you fill in the parameter values.

image

After you click on Send, another dialog will pop up showing you the response.

image

Adding Request Headers

You can add additional request headers by clicking “Add Header”. For example, you can add the accept header “text/xml” to ask for XML.

image

And sure enough, your Web API returned the content as XML.

image

Providing Request Body

For methods like POST, you can provide the body in the Body section. Note that it will be prepopulated with the samples from Help Page so you don’t need to do any copy-pasting.

image

And you can select different samples based on the supported media types. For instance, selecting application/xml will pull in the XML sample. Note that the content-type and content-length headers are updated accordingly.

image

You can change the content of the body and the content-length header will change as you type!

image

 

Update: The source code is now hosted at: https://github.com/yaohuang/WebApiTestClient

 

Hope you enjoy the Web API Test Client!

Yao

Comments (64)

  1. Wouter de Kort says:

    Works great 🙂

    Thank you!

  2. Nate Taylor says:

    Looks like there is a bug where it assumes you're running at the root.  For our project (on IIS) our base URL for the API is localhost/business

    When I wired up fiddler I saw that it was trying to do a get to localhost/dashboard instead of locahost/business/dashboard.

    I looked to find your source code to see if I could do a pull request, but was unable to find it.

  3. @Nate Taylor

    Thanks for pointing out the issue. I've pushed another version containing the fix on NuGet. Please give it a try.

    Meanwhile I'll find a host for the source code and will update the post with the location.

    Thanks,

    Yao

  4. Nate Taylor says:

    @Yao – Got your latest & it's working great. Thanks.

  5. Nate says:

    Not to be a pain, but any chance you could make it work with IE8?  Right now it doesn't hide the test client dialog, it just shows it at the bottom of the page. Also, the button is the full window width, not like on Chrome where it's small and off to the side.

  6. @Nate Taylor

    Thanks for trying it out! I'll look into the IE8 issue later this week.

  7. I've uploaded the source at github.com/…/WebApiTestClient

    Feel free to take a look and contribute!

    Thanks,

    Yao

  8. Atul Katare says:

    Hi Yao

    once again great works..

    I have one problem with dynamic route

    we are getting some values from URI

    we have diffeerent route template like {countryName}/{stateName}/{controller}/User/{userName}

    So, how to map this route template with Controller

    here is my controller code

    namespace Usa.Pa.Controlller

    {

    class UserController : ApiControlller

    {

    Public HttpResponseMessage Get( string userName)

        {

            return new HttpResponseMessage ();

        }

    }

    }

    here is URI for test : http://Testerver:12345/Usa/pa/User/TestUser

    I am getting zero records in apiDescriptions

    var apiDescriptions =  apiConfiguration.Services.GetApiExplorer().ApiDescriptions

    Please help me how to resolved this issue.

    Thanks-

  9. Hi Atul Katare,

    Maybe you're hitting this issue? (aspnetwebstack.codeplex.com/…/865)

    The work around for now would be adding the route variables to the parameter. E.g. Get(string userName, string countryName, string stateName). We will consider fixing it in a future release.

    Thanks,

    Yao

  10. Atul Katare says:

    Thanks Yao

    we have same problem.

    Do you have any plan for future release?

    Thanks-

  11. Hi Atul Katare,

    I don't have a specific date yet but you can subscribe to our CodePlex site (aspnetwebstack.codeplex.com) for announcements and updates.

    Thanks,

    Yao

  12. Atul says:

    Hi Yao,

    One more question

    I have define my controlller and route in another project so how can I display help page with out adding reference in Reference folder.

    Thanks-

  13. Atul says:

    Hi Yao,

    I have resolved this issue using IAssembliesResolver

    Thanks-

  14. Atul says:

    Hi Yao,

    I have defined three route , each route defined for separate method (GET,PUT, POST)

             config.Routes.MapHttpRoute(

                   "types_get",

                   "Types/{dataTypeId}",

                   new { controller = "DataTypes", dataTypeId = RouteParameter.Optional });

               config.Routes.MapHttpRoute(

                   types_insert",

                   "DataTypes/Insert",

                   new { controller = "DataTypes" });

               config.Routes.MapHttpRoute(

                   "types_Update",

                   "DataTypes/Update",

                   new { controller = "DataTypes" });

    here is my Controller code

    public class DataTypesController : ApiController

       {

           public DataType Get(string dataTypeId)

           {

               return DataTypes.FirstOrDefault(x => x.DatatypeId == dataTypeId);

           }

           public void Put([FromBody] DataType dataType)

           {

           }

           public void Post([FromBody] DataType dataType)

           {

           }

    }

    It displaying nine Records on Web Api Help page, here I am expecting only three records should be display on the page.

    Please advise if I doing something wrong in my code.

    Thanks-

    Atul

  15. Atul says:

    Hi Yao,

    One more issue with Optional Parameter.

    I have common Get Method if I pass the value to dataTypeId it will return single record based on the dataTypeId and if I pass the blank value or null, I am expecting all record should return.

    If I am passing blank value in the dataTypeId variable its take the dataTypeId as "{dataTypeId }" value and I am getting zero record

    Here is My Route, controller Code and URI

    config.Routes.MapHttpRoute(

                  "types_get",

                  "Types/{dataTypeId}",

                  new { controller = "DataTypes", dataTypeId = RouteParameter.Optional });

    public HttpResponseMessage Get(string dataTypeId = null)

    {

    }

    URI : GET : => USA/V1/PA/DataTypes/{dataTypeId}

    Do you have any idea about to resolved this issue?

    Thanks-

    Atul

  16. Hi Atul,

    Re the routes, you need to add a HttpMethodConstraint to limit the HTTP method on each route. Otherwise all nine APIs shown on the Help Page can actually be reached.

    Have something that look like the following and do that for every route with different HTTP methods.

    config.Routes.MapHttpRoute(

                  "types_get",

                  "Types/{dataTypeId}",

                  new { controller = "DataTypes", dataTypeId = RouteParameter.Optional },

                  new { constrain = new System.Web.Http.Routing.HttpMethodConstraint(HttpMethod.Get) });

    Re the optional parameter, there is no blank value, {dataTypeId} simply act as an variable and the value for that variable is either string or null. Passing the {dataTypeId} will literarily be taken as string.

    Hope this helps,

    Yao

  17. Atul says:

    Hi Yao,

    Thanks your reply it work as expected.

    another issue when I pass the dataTypeId or userName as "Tom.Stig" it throw an exception "Internal Server error"

    Is there any specific reason for this error. I think its encoding related issue which is not allow DOT

    Thanks-

    Atul

  18. John says:

    I needed to write code to clear parameters that are not entered from the uri when we use self.sendRequest:

               for(param in self.UriParameters)

               {

                   uri = uri.replace('{' + self.UriParameters[param].name + '}', '');

               }

    Otherwise great!

  19. John says:

    Make That:

               for(param in self.UriParameters)

               {

                   var value = self.UriParameters[param].value();

                   uri = uri.replace('{' + self.UriParameters[param].name + '}', value);

               }

    When a body is included it didn't replace the value in the uri

  20. Whale Helper says:

    That's handy. It's especially good for people developing using the API. There's nothing like seeing the API work in your browser, to help you figure out how to get it work for you.

    Often it's even helpful to have a test page before the API itself is built because then you can use it to test the API out.

    There is now a web site that provides this solution fore free, so that you can create and run your own test suites for an API directly in your browser without any coding. And you can even share them with other developers. But, you should check it out. It's at http://www.quadrillian.com Keep up the good work.

  21. Bruce says:

    Hi Yao,

    I use Web API for VB.

    Use "Install-Package WebApiTestClient" then found reinstall all *.cs and *.cshtml in my Web API project.

    Can you provide VB Version?

    Thanks

  22. SocialMitch says:

    Thank you for this.  Love it.  Saves me a lot of time … and it actually looks very nice.  Good job!!

  23. Chris Towles says:

    Thanks for your work on this Yao, Really great stuff you have created for the WebAPI community.

  24. Eli says:

    I've downloaded the package, added the items in step 2, but what url do I have to enter so that I can see the page titled "asp.net web api"?

    Thanks !

  25. Hi Eli,

    It's the Help Page URL. And by default, it's "http://<your_application_base_url>/help&quot;.

  26. Eli says:

    Hi Yao,

    I'm using localhost, so I tried the same url that is working for the local website and I get an error page starting with:

    The view 'Index' or its master was not found or no view engine supports the searched locations. The following locations were searched:

    ~/Views/help/Index.aspx

    ~/Views/help/Index.ascx

    ~/Views/Shared/Index.aspx

    ~/Views/Shared/Index.ascx

    ~/Views/help/Index.cshtml

    ~/Views/help/Index.vbhtml

    ~/Views/Shared/Index.cshtml

    ~/Views/Shared/Index.vbhtml

    Thanks for the quick reply !

    Elir

  27. Eli says:

    …This is the url: http://localhost:19083/help

    Thanks 🙂

  28. For some reason, I'm getting a ko is undefined error in the JS file.  What dependancy am I missing?

  29. Hi Eli,

    Did you registered the help page area? In the Global.asax.cs make sure you call AreaRegistration.RegisterAllAreas()

  30. Hi Christopher,

    Do you have the knockoutjs installed?

  31. Matt Cochrane says:

    It's excellent, but it took me hours to figure out why it worked when posting JSON content but not for posting XML content.  It turns out there is a bug in how it renders DateTime values. It is supposed to be ISO 8601 format, eg "2013-07-30T14:13:04.4514602+01:00" but the test dialog renders the sample data dates like "2013-07-30T14:13:04.4514602 01:00" (the "+" has changed to a space). This upsets the XML serialization (I don't know why it doesn't break the JSON serialization). When I manually correct it in the dialog box, XML content works like a charm.

  32. Matt Cochrane says:

    A "nice to have" would be if the "accept" header was included by default, maybe with dropdown options to choose between xml and json.

  33. Bruce says:

    Hi,

    Can you add a ReadMe.txt to package, then add this content:

    Note that you add the @Html.DisplayForModel("TestClientDialogs") after the <div> and @Html.DisplayForModel("TestClientReferences") inside the Scripts section.

    I forgot it in every new project, then I will back you blog. XD

  34. Jasenko says:

    Hello,

    I'm trying to add cookie inside header but somehow I'm not able to. I've added it successfully using REST client for fiddler adding it inside header like : Cookie : CookieName=CookieValue. Here's image from api test client

    http://i.imgur.com/bSAcIns.png.

    Thank you

  35. Matt says:

    I am getting a few javascript errors 🙁

    SCRIPT5007: Unable to get property 'length' of undefined or null reference

    jquery-2.0.3.js, line 564 character 4

    SCRIPT5007: Unable to get property 'removeClass' of undefined or null reference

    jquery-ui-1.9.2.js, line 692 character 4

    Any ideas as to why the JS would fail? Is there any other setup required after the nuget package install?

  36. Giuseppe says:

    Hi Yao, do you know it is not working well in VS2013 ?

  37. TB L says:

    Looks like it's broken when added to the VS2013 SPA solution.

    Error 3 'SPA.Tests.Areas.HelpPage.XmlDocumentationProvider' does not implement interface member 'System.Web.Http.Description.IDocumentationProvider.GetResponseDocumentation(System.Web.Http.Controllers.HttpActionDescriptor)' D:srcSPASPA.TestsAreasHelpPageXmlDocumentationProvider.cs 14 18 SPA.Tests

    Error 4 'SPA.Tests.Areas.HelpPage.XmlDocumentationProvider' does not implement interface member 'System.Web.Http.Description.IDocumentationProvider.GetDocumentation(System.Web.Http.Controllers.HttpControllerDescriptor)' D:srcSPASPA.TestsAreasHelpPageXmlDocumentationProvider.cs 14 18 SPA.Tests

  38. Mary says:

    Has anyone ported this to work with Yao's help page on a self hosted server?blogs.msdn.com/…/making-asp-net-web-api-help-page-work-on-self-hosted-services.aspx

  39. Trevor Daniel says:

    Hi. When I found this it looked just perfect.

    I have tried installing it on a VS2013 MVC5 Web API 2 solution and I get no errors but when I click the "Test API" button nothing happens.

    Has anyone got it working recently please?

  40. Sam says:

    Just got it working today. I am converting my solution from ServiceStack to WebAPI and had to start [over] with fresh solutions, but it works great

  41. Trevor Daniel says:

    Finally got it working. I fixed it by creating a clean mvc5 webapi, installing all the nugget updates and THEN adding this.

    Works perfectly.

    And, like Sam, I am on this quest because I have dropped Service Stack… LOL

  42. Fede says:

    It works great!!

    It's a shame you used jQuery UI instead of Bootstrap (already integrated with ASP.NET templates).

    Anyway, thank you very much for the contribution!

  43. learning_to_code says:

    How can I do this with Visual Studio 2013? I am unable to add the Nuget package.

  44. Martin says:

    This test client is awesome, and I have used it for several project with great pleasure! I would love to see a new version that works with WebAPI 2 out of the box? Even more awesome would be one based on Angular/Bootstrap instead of Knockout/Jquery UI? Any chance of a new version?

  45. Rune Hansen says:

    I would also like to see see a new version that works with WebAPI 2 out of the box. So far I haven't been able to get it to work with WebAPI 2. A working code example is always good 🙂

  46. Rich Hosek says:

    Trying to install in a Web API 2 project via NuGet and it fails:

    Updating 'Microsoft.AspNet.WebApi.WebHost 5.1.2' to 'Microsoft.AspNet.WebApi.WebHost 4.0.20710.0' failed. Unable to find a version of 'Microsoft.AspNet.WebApi' that is compatible with 'Microsoft.AspNet.WebApi.WebHost 4.0.20710.0'.

    Seems like it's trying to downgrade my WebHost.

  47. wuchangx@gmail.com says:

    博主很久没更新,我做了些修改,让其能在 Web API HelpPage >=5.1 版本上运行。

    github.com/…/WebApiTestClient

    http://www.nuget.org/…/WebApiTestOnHelpPage

    相关的修改也已经 push 到github

  48. Troy P says:

    Awesome work man!  This is something that should be native to VS.

  49. John Mark Howell says:

    I tried it in a WebAPI2, .Net 4.5.1, VS 2013 solution and hit this error:

    Unhandled exception at line 132 of WebApiTestClient.js.  JavaScript runtime error: Object doesn't support property or method 'dialog'.

    Suggestions?

  50. Pooja says:

    I am not able to access TEST API feature on IIS server. Kindly help

  51. Nur says:

    It is very nice. But, I don't know how to add basic authentication. Can you help?

    Thanks,

  52. Seggie1 says:

    Very nice. works well

  53. Css issue? says:

    I have the client working great, love it.  The only issue I have is the layout.  For some reason, I think my css is messed up as I get no nicely defined window, but the test pops on top of the existing page with no back ground color so it is very difficult to see and use.

  54. Adam S. says:

    Hello Yao,

    I am using this test client and it is wonderful! On top of that your other 3 blog posts about customizing the ASP.NET Web API help page were a tremendous help! I had a question though:

    Is it possible to wire up the help page to use different connection strings than the root project? I assumed that if I provided different connections strings in the Help page web.config that they would take precedent on the help page, but that doesn't seem to be the case. Any ideas?

  55. Junli A. says:

    Hi Yao,

    The Test API button did not show up for my app. It had an error "NuGet Package restore failed for project Miscellaneous Files: Value cannot be null or an empty string. Parameter name: root. 0 0".

    After deleting the visual studio solution user options file (.suo) and then restarting VS, it can be compiled, but the 3 js files are versions above what you have in here. If I update them, the web api won't work, as the MVC depends on them.  Any idea what I can do  in order to use it?

  56. havid says:

    Hi Yao,

    Where is the  Json.Encode    on TestClientDialogs.cshtml

  57. Casey G says:

    This is really cool stuff. There are two things I would like to be able to do that I have not been able to find so far:

    1. Generate an offline document (Either chm, a zip file of html, or pdf) of the Web API document, as opposed to something that is dynamic at run time.

    2. Add in sections for the Token endpoint for thing like Bearer Authentication.

  58. register007 says:

    Hi Yao – this test client works great in my first project but the pop-up window is missing from my second project, i.e., the text generated by the test client overwrites the existing screen.

    The test client still works though  – it retrieves and display the correct information and the buttons work as expect. I've tried comparing the files from the Areas folder in the two projects but haven't found the cause – any ideas?

    Thanks for you help!

  59. Ustes G says:

    If anybody is using VB.Net for webapi I have a version here:

    github.com/…/WebApiTestClient.VB

    I am removing jquery-ui & using bootstrap.

  60. UstesG says:

    VB.Net version that uses Bootstrap.

    github.com/…/WebApiTestClient.VB

  61. xpy0928 says:

    WebAPITestClient测试是个好工具,楼主怎么不继续更新呢?现在想借助该工具测试WebAPi但是 不支持MVC5了。

  62. dbowser says:

    I had this working before then had configuration issues so reinstalled packages and using the latest.

    Now, when I click on the 'Test API' button it puts the text of the 'pop up' pages over the text of the underlying page with no background so it is all just jumbled together. Otherwise it seems to work. What am I missing here?

  63. ALOB says:

    dbowser – this is due to an update to the JQuery.UICombined nuget package – if you downgrade that package then the styles return

  64. Hasse says:

    Hi Yao!

    Nice package, Ive been using it for a couple of weeks.

    But last week something happened, now the modal box CSS is 'see through'… if you could post an update it would be great? 🙂