Compartilhar via


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

  • Anonymous
    December 02, 2012
    Works great :) Thank you!

  • Anonymous
    December 03, 2012
    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.

  • Anonymous
    December 03, 2012
    @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

  • Anonymous
    December 04, 2012
    @Yao - Got your latest & it's working great. Thanks.

  • Anonymous
    December 04, 2012
    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.

  • Anonymous
    December 04, 2012
    @Nate Taylor Thanks for trying it out! I'll look into the IE8 issue later this week.

  • Anonymous
    December 05, 2012
    I've uploaded the source at github.com/.../WebApiTestClient Feel free to take a look and contribute! Thanks, Yao

  • Anonymous
    February 28, 2013
    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-

  • Anonymous
    February 28, 2013
    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

  • Anonymous
    February 28, 2013
    Thanks Yao we have same problem. Do you have any plan for future release? Thanks-

  • Anonymous
    March 01, 2013
    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

  • Anonymous
    March 07, 2013
    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-

  • Anonymous
    March 07, 2013
    Hi Yao, I have resolved this issue using IAssembliesResolver Thanks-

  • Anonymous
    March 10, 2013
    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

  • Anonymous
    March 10, 2013
    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

  • Anonymous
    March 12, 2013
    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

  • Anonymous
    March 18, 2013
    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

  • Anonymous
    March 25, 2013
    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!

  • Anonymous
    March 25, 2013
    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

  • Anonymous
    March 31, 2013
    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 www.quadrillian.com Keep up the good work.

  • Anonymous
    April 16, 2013
    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

  • Anonymous
    April 20, 2013
    Thank you for this.  Love it.  Saves me a lot of time ... and it actually looks very nice.  Good job!!

  • Anonymous
    May 10, 2013
    Thanks for your work on this Yao, Really great stuff you have created for the WebAPI community.

  • Anonymous
    May 27, 2013
    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 !

  • Anonymous
    May 28, 2013
    Hi Eli, It's the Help Page URL. And by default, it's "http://<your_application_base_url>/help".

  • Anonymous
    May 28, 2013
    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

  • Anonymous
    May 28, 2013
    ...This is the url: http://localhost:19083/help... Thanks :-)

  • Anonymous
    June 04, 2013
    For some reason, I'm getting a ko is undefined error in the JS file.  What dependancy am I missing?

  • Anonymous
    June 06, 2013
    Hi Eli, Did you registered the help page area? In the Global.asax.cs make sure you call AreaRegistration.RegisterAllAreas()

  • Anonymous
    June 06, 2013
    Hi Christopher, Do you have the knockoutjs installed?

  • Anonymous
    July 29, 2013
    The comment has been removed

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

  • Anonymous
    August 19, 2013
    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

  • Anonymous
    August 22, 2013
    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

  • Anonymous
    October 15, 2013
    The comment has been removed

  • Anonymous
    October 22, 2013
    Hi Yao, do you know it is not working well in VS2013 ?

  • Anonymous
    November 01, 2013
    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

  • Anonymous
    November 03, 2013
    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

  • Anonymous
    February 03, 2014
    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?

  • Anonymous
    February 04, 2014
    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

  • Anonymous
    February 04, 2014
    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

  • Anonymous
    April 22, 2014
    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!

  • Anonymous
    April 25, 2014
    How can I do this with Visual Studio 2013? I am unable to add the Nuget package.

  • Anonymous
    May 06, 2014
    The comment has been removed

  • Anonymous
    May 14, 2014
    The comment has been removed

  • Anonymous
    May 20, 2014
    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.

  • Anonymous
    June 17, 2014
    博主很久没更新,我做了些修改,让其能在 Web API HelpPage >=5.1 版本上运行。 github.com/.../WebApiTestClient www.nuget.org/.../WebApiTestOnHelpPage 相关的修改也已经 push 到github

  • Anonymous
    August 07, 2014
    Awesome work man!  This is something that should be native to VS.

  • Anonymous
    August 13, 2014
    The comment has been removed

  • Anonymous
    August 18, 2014
    I am not able to access TEST API feature on IIS server. Kindly help

  • Anonymous
    August 28, 2014
    It is very nice. But, I don't know how to add basic authentication. Can you help? Thanks,

  • Anonymous
    October 16, 2014
    Very nice. works well

  • Anonymous
    November 13, 2014
    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.

  • Anonymous
    November 24, 2014
    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?

  • Anonymous
    February 03, 2015
    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?

  • Anonymous
    April 08, 2015
    Hi Yao, Where is the  Json.Encode    on TestClientDialogs.cshtml

  • Anonymous
    June 02, 2015
    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.
  • Anonymous
    June 05, 2015
    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!

  • Anonymous
    October 22, 2015
    If anybody is using VB.Net for webapi I have a version here: github.com/.../WebApiTestClient.VB I am removing jquery-ui & using bootstrap.

  • Anonymous
    October 22, 2015
    VB.Net version that uses Bootstrap. github.com/.../WebApiTestClient.VB

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

  • Anonymous
    January 12, 2016
    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?

  • Anonymous
    January 19, 2016
    dbowser - this is due to an update to the JQuery.UICombined nuget package - if you downgrade that package then the styles return

  • Anonymous
    February 23, 2016
    The comment has been removed