Showing posts with label ASP.NET Web API. Show all posts
Showing posts with label ASP.NET Web API. Show all posts

Thursday, October 6, 2016

Creating lowercase routes in ASP.NET Web API

When it comes to creating lowercase routes in ASP.NET Web API, there is no built-in facility to automatically lowercase all of your routes as is the case with ASP.NET MVC.

However, you can still solve this issue without resorting to Attribute-based routing and manually writing all of your routes in lowercase.

This can be accomplished through Custom Route Constraints.  In this instance, you will want to create a Custom Route Constraint which simply translates all of the default ASP.NET Web API routes into their corresponding lowercase version.

You can write a LowercaseRouteConstraint as follows:


Creating Route Constraints using Attribute-based Routing in ASP.NET Web API

When you are writing your Web API methods, you may encounter a situation whereby you have two different methods that need to be distinguished from each other through their routes?

For example, if you have a method GetById(int id) and GetById(string id), how do you distinguish between these 2 routes when documenting your Web API using Attribute-based routing?

Well, through Route Constraints of course!

https://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2#constraints

Therefore, you can then have Web API methods like the following:


Tuesday, October 4, 2016

Is .NET Core ready for Business/Enterprise development?

If you have read all of the hype on .NET Core/ASP.NET Core, you may be wondering if ASP.NET Core is TRULY ready for Business/Enterprise development.

The best way to judge this for yourself is to read the recent MSDN Blogs:

https://blogs.msdn.microsoft.com/dotnet/2016/09/21/reusing-configuration-files-in-asp-net-core/

In this article, you can see that you have to COMPLETELY re-write functionality for reading configuration files if you decide to move to ASP.NET Core 1.0!!

Next up, if you look at the roadmap for .NET Core, you will see that there are several enhancements already planned for an upcoming release of .NET Core:  https://blogs.msdn.microsoft.com/dotnet/2016/09/26/introducing-net-standard/

Therefore, Microsoft is basically acknowledging that .NET Core 1.0 is NOT ready for most businesses/enterprises to adopt since a lot of the functionality that developers have used in the past with ASP.NET MVC 5 and ASP.NET Web API 2.2 and other features in the .NET Framework are simply not available in .NET Core today.

This is rather unfortunate since .NET Core brings a lot of exciting features to the table including cross-platform compatibility.  However, the fact is that most developers will end up writing a TON of code to fill in the gaps currently left open by .NET Core 1.0.

On the bright side, much like ASP.NET MVC in its infancy several years ago, it seems that .NET Core will evolve rather quickly to be able to be used in the near future.  I am crossing my fingers and hoping that these features get added sooner rather than later, but given how many years I have been working with Microsoft products, I know not to have too many high expectations.  After all, there are features in some products that took 10 or more years before they were introduced into platforms such as SQL Server, Visual Studio, Team Foundation Server etc. and even in ASP.NET MVC 5 today, there are many features lacking that make it as usable a web development framework as ASP.NET Web Forms...

Friday, September 30, 2016

Using FluentValidation for ASP.NET Web API

If you want to implement validation for your ASP.NET MVC Web Application, this is easily done in a number of ways using ASP.NET MVC's own validation mechanisms as well as using NuGet packages such as FluentValidation for ASP.NET MVC: https://github.com/JeremySkinner/FluentValidation

Unfortunately, even though there is also a FluentValidation NuGet package for ASP.NET Web API (https://www.nuget.org/packages/FluentValidation.WebAPI/), there is no corresponding documentation for ASP.NET Web API on the FluentValidation Wiki!(https://github.com/JeremySkinner/FluentValidation/wiki)

Thankfully, though, there are a few articles which address just how to accomplish this using the FluentValidation library for ASP.NET Web API!

http://www.justinsaraceno.com/2014/07/fluentvalidation-with-webapi2/

https://www.exceptionnotfound.net/custom-validation-in-asp-net-web-api-with-fluentvalidation/



Understanding Attribute-based routing in ASP.NET Web API

If you are new to Web API, you may not completely understand how Attribute-based routing in ASP.NET Web API works.

The documentation for ASP.NET Web API Attribute-based routing is rather sparse and very confusing at times.

Therefore, I thought I would provide some clarifications on Attribute-based routing for anyone who is developing with ASP.NET Web API:


  1. Attribute-based routing, by default, takes precedence over any routing rules defined in WebApiConfig.cs
  2. When defining your Attribute-based routes, there is no way to enforce having all of your routes defined in lowercase or camel-case, therefore, it is best to simply standardize the route name casing your will be using and ensure that the entire development team is aware of this standard and follows it throughout all your development.  A good way to publish these standards is through a ReadMe.md file in source control or publishing it on an Intranet Wiki site.
  3. Once you define a [RoutePrefix] attribute at the top of your Web  API Controller class, you MUST define Attribute routes for all of the other methods in your Web API Controller.
  4. For default named methods such as Get, Put, Post and Delete, you will still have to define the default attribute route of [Route("")]
  5. Even when using convention-based naming, it is best to decorate your Web API method names with their appropriate action types such as [HttpGet], [HttpPut], [HttpPost] and [HttpDelete]
  6. For methods such as Get and Delete, you usually DO define route parameters.  Therefore, a GetById or a Delete method, might have the following Route attribute defined: [Route("{id}")]
  7. For methods such as Post and Put, you usually DO NOT define any route parameters.  This is because the assumption is that you are posting a model using the [FromBody] attribute, so a Post or Put operation assumes that you are not sending values in the Url.
  8. Any parameters which are not explicitly defined in the route will automatically end up with query-string based routes rather than RESTful routes.  Therefore, it is best to define ALL parameters in your attribute based routes.  Ex: [Route("{id}/details/{detailsid}")]
  9. Parameter names DO make a difference in Web API!  Therefore, if your parameter is named myId, then you need to define a route as follows: [Route("{myId}")].  If you define a route as follows: [Route("{id}")] this will NOT work!
  10. You CAN have the same [RoutePrefix] on multiple Web API Controllers!  Therefore, if you want to split up your functionality across multiple Web API Controllers, you can readily do so and just adjust your route attributes accordingly on each of your Web API methods.
  11. If you have inheritance hierarchies in your Web API controllers, you need to standardize the conventions for your Attribute-based routes such as all Details for a particular class be accessed using a Route such as the following: [Route("{id}/details")]
  12. When performing Get requests which receive a collection of all the items, the standard is to simply have an empty route: [Route("")].  However, if you want to retrieve a specific item, then you should parameterize the route: [Route("{id}")].  These can be distinguished by having method names such as Get and GetById.  
  13. If you install Web API Help or Swagger for your ASP.NET Web API project, you can review all of your routes to make sure they are correct in an easy to view web page, by either navigating from your web browser to either /help or /swagger in the root of your Web API project.  Therefore, you might have a Url such as http://localhost/MyWebAPI/help or http://localhost/MyWebAPI/swagger
That should be pretty much all you need to get started developing your ASP.NET Web API Web Applications using Attribute-based routing!

Tuesday, August 30, 2016

Server-side paging with ASP.NET Web API and Kendo UI Grids

If you need to implement a custom server-side paging solution with Kendo UI, it may not be readily obvious as to how to accomplish this!

Kendo UI has some code samples which partially addresses this scenario: https://github.com/telerik/ui-for-aspnet-mvc-examples/tree/master/grid/custom-ajax-binding/KendoGridCustomAjaxBinding

However, this example is tightly coupled to Entity Framework and does not work so well with ASP.NET Web API...

So how exactly can you adapt the Controller code sample to your own needs that work with ASP.NET Web API?

First of all, you need to make sure your Kendo Grid is setup as follows:
Notice that you have to set ServerOperation(true)

Next, you have to set up your Controller code as follows:

That is all there is to it!

Thursday, August 25, 2016

Using Unity IoC with constructor parameters

I recently decided to switch my IoC container from Ninject to Unity for my ASP.NET Web API Web Application because the Ninject IoC container has poor support for Web API and has not been updated/refreshed in several years.

So, naturally, when I began switching my code over from Ninject over to Unity, one of the questions that immediately came up was how to use constructor parameters for my types in Unity?

Well, after doing some quick searching and experimentation, I came up with this solution:


It is as simple as that!

Monday, August 22, 2016

Mocking HttpClient in your ASP.NET Web API Unit Tests

If you use HttpClient in your Unit Tests, you may encounter a great deal of difficulty with using this object since this object is not easily mocked using a Mocking Framework such as Moq.  In fact, you may encounter an error message such as the following:


There are a great number of solutions posted on the Internet on how to resolve this issue by creating a custom HttpMessageHandler and then passing this in the constructor of the HttpClient to create the HttpClient object for Unit Testing.

However, a clever developer has already provided a very handy NuGet package to allow you to do just that!  https://github.com/richardszalay/mockhttp

MockHttp is just one particular NuGet package that supports Unit Testing of the HttpClient.  There are other such as HttpClient.Helpers https://github.com/PureKrome/HttpClient.Helpers

However, the use of MockHttp is very intuitive and I highly prefer using it in my Unit Tests.

One of the things that I like to do, however, is use frameworks such as NBuilder or AutoFixture to help me generate test data rather than manually type this information into my Unit Tests myself.  But, one of the problems with using an object such as HttpResponseMessage is that it does not lend itself well to generating all of the properties needed to pass a Unit Test such as setting the Content of the HttpResponseMessage.

Therefore, I had to use a solution such as the following to get my entire Unit Test to work:


Friday, August 12, 2016

HttpConfiguration does not contain a definition for EnableQuerySupport

I was recently attempting to add OData support to my ASP.NET Web API application when I encountered the following error message:



My friend then pointed me to this StackOverflow forum posting: http://stackoverflow.com/questions/27860997/where-does-webapi-2-2-odata-v4-enablequery-apply

This changed how to use the EnableQuery attribute globally in my WebApiConfig.cs file as follows:


Wednesday, August 10, 2016

Adding OData support to ASP.NET Web API

If you want to support operations such as filtering and paging easily in your ASP.NET Web API web applications, you will probably want to add OData support to your ASP.NET Web API application as outlined in this article: http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/odata-v4/create-an-odata-v4-endpoint

Once you have added OData support to your ASP.NET Web API web application, you can then review your options for querying your OData as outlined in these articles:

http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/supporting-odata-query-options#server-paging

http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/using-select-expand-and-value


ASP.NET MVC and ASP.NET Web API Code Samples

If you are looking for code samples on how to accomplish various scenarios using either ASP.NET MVC or ASP.NET Web API, you can find examples provided directly by Microsoft here: https://aspnet.codeplex.com/SourceControl/latest#Samples/ReadMe.txt

They have code samples ranging from authentication to attribute-based routing to using OWIN/Katana and various other scenarios!

Saturday, August 6, 2016

Creating Custom Scaffolding Templates for ASP.NET MVC and ASP.NET Web API

If you need to heavily customize the out-of-the-box templates that come with ASP.NET MVC and ASP.NET Web API, you can either create a brand new T4 Templates project or simply use the CodeTemplates directory functionality for Scaffolding that is already available with ASP.NET MVC and ASP.NET Web API!

You can read more about creating your own Custom Scaffolding Templates below:

http://weblogs.asp.net/imranbaloch/customizing-the-asp-net-mvc-5-web-api-2-scaffolding-templates

http://www.hanselman.com/blog/ModifyingTheDefaultCodeGenerationscaffoldingTemplatesInASPNETMVC.aspx

https://www.credera.com/blog/technology-insights/microsoft-solutions/create-custom-scaffold-templates-asp-net-mvc/

All of these articles refer to paths from earlier versions of Visual Studio, so if you are wondering about the correct path for Visual Studio 2015, it is this:

C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\Web\Mvc\Scaffolding\Templates

Inside that folder, you will find the following folder structure which displays all of the possible default scaffolding templates that you can override by bringing it directly into your solution:



Once you have your Scaffolding templates in place, you can simply right click in your ASP.NET MVC or ASP.NET Web API project and select Add --> New Scaffolded Item:





This will then use your own custom Scaffolding Template instead of the out-of-the-box Scaffolding templates that ship with Visual Studio!  In addition, you can also add new Scaffolding templates as well that can further extend what ships with Visual Studio!

How cool is that??

Friday, August 5, 2016

Unit Testing ASP.NET Web API using Attribute-based Routing

If you review any Unit Test code samples for ASP.NET Web API, you will find examples on how to Unit Tests when using CreatedAtRoute but they only refer to using the Default Routing rules available in WebApiConfig.cs.

So what do you do if you are using Attribute-based routing?

Well, while this scenario is poorly documented, there is a solution for this as well!

You start by using the Route Name attribute on  your Post method as follows:


Now, if you want to Unit Test that code, you can do something like the following:

That is all that is needed in order to support Unit Testing with Attribute-based routing!

Tuesday, August 2, 2016

Customizing ASP.NET Web API Help

If you are working with ASP.NET Web API Help, chances are that you will want to customize the output of Web API Help even after enabling Xml Comments.

Unfortunately, there are not a lot of articles published out there which shows you the ins and outs of customizing ASP.NET Web API Help, but there are a few!

Here are a few articles that go through how to make some basic customizations to ASP.NET Web API Help:

https://blogs.msdn.microsoft.com/yaohuang1/2012/09/30/asp-net-web-api-help-page-part-1-basic-help-page-customizations/

https://blogs.msdn.microsoft.com/yaohuang1/2012/10/13/asp-net-web-api-help-page-part-2-providing-custom-samples-on-the-help-page/

https://blogs.msdn.microsoft.com/yaohuang1/2012/12/10/asp-net-web-api-help-page-part-3-advanced-help-page-customizations/

ResponseType attribute in ASP.NET Web API

I was recently introduced to the ResponseType attribute for documenting my ASP.NET Web API Web Applications.  This was a feature that I was not aware of previously and after discovering it, found rather handy!

If you read the MSDN documentation for this attribute, you will see that it is used to describe the Web API for Web API Help: https://msdn.microsoft.com/en-us/library/system.web.http.description.responsetypeattribute(v=vs.118).aspx

This article addresses the ResponseType attribute as well as other Data Annotations much more clearly: http://www.strathweb.com/2014/01/return-types-action-parameters-and-data-annotations-now-available-in-web-api-2-1-help-page/

Therefore, you can use all of these attributes to more clearly your Web API Urls!

Friday, July 29, 2016

Sequence contains no elements while using Ninject

I was recently working on an ASP.NET Web API project that used Ninject as its IoC container when I was suddenly faced with this error message:


As you can see from above, the error message provided no real insight as to what might be the root cause of the problem!

Therefore, I decided to do some further digging into the documentation for Ninject and came across this article: https://github.com/ninject/Ninject.Web.Common/wiki/Setting-up-an-IIS-hosted-web-application

Based on this documentation, I needed to make sure that my NuGet package reference to Ninject.Web.Common.WebHost was correct.

Of course, when I went into my packages.config file, the NuGet package reference was listed and it was also listed as installed in NuGet Package Manager.

However, based on the error message, I figured there was some problem with this installation and its corresponding references so I removed the line from packages.config in my Web API project and re-installed the Ninject.Web.Common.WebHost NuGet package reference.

As you can already probably guess, this did the trick for me and resolved this very elusive Ninject problem!!

NOTE:  Another time I have encountered this problem has been due to invalid assemblies in the bin folder of my ASP.NET Web API project.  Simple deleting the bin folder of my ASP.NET Web API project and rebuilding my solution also resolved the problem!

Monday, July 25, 2016

Ensure that you have defined a binding for HttpConfiguration only once

I was recently working on adding Ninject to an ASP.NET Web API web application, when I suddenly encountered the following error message:



Well, as it turns out, after adding the Ninject.Web.WebApi.WebHost NuGet package reference, I also had a reference to Ninject.Web.WebApi which was causing the HttpConfiguration to be injected twice!

I had originally added the Ninject.Web.WebApi.WebHost NuGet package reference so that the NinjectWebCommon.cs file would be added automatically to my App_Start directory for injecting my dependencies.

Once that file was added, I no longer needed this NuGet package reference, so I went ahead and removed it and I could successfully browse my ASP.NET Web API Web Application once again!

Tuesday, July 12, 2016

The problems with Attribute-based routing in ASP.NET Web Api

I was recently working on a project whereby Attribute-based routing was being used in conjunction with Partial Classes for Web API Controllers.

While I will not going into the details of this inherent design flaw, it allowed me to better understand the problems inherent with Attribute-based routing and why so many developers prefer defining explicit routes in the WebApiConfig.cs class file.


  1. The first thing I noticed as an inherent limitation of Attribute-based routing was that you can only define the RoutePrefix attribute on a single class instance even in a partial class scenario.  Therefore, if you have a partial class that splits across 2 files, this means that the RoutePrefix can only exist on one of the 2 files, thus making it more difficult to understand what is the RoutePrefix definition when switching between the 2 files.  Now, just imagine, if that partial class is split across 3 or more files!
  2. Another thing that I noticed was Attribute-based routing does not work perfectly on all methods even when defining a RoutePrefix in a class file.  I had one instance of a class that was using more than 8 parameters in the method definition, and it also had no route attribute assigned to it.  In this instance, the RoutePrefix was being totally ignored by ASP.NET Web API and instead only the Default Route was being used for this particular method.  Scenarios like this make Attribute-based routing even more troublesome.
  3. In simple instances where you are using the RoutePrefix on a class, if you forget to decorate your other methods with the Route attribute, once again these routes will not follow the Attribute-based routing convention and revert to the Default Route defined in WebApiConfig.cs.

These are just a few of the more blatant reasons that I discovered while working with Attribute-based routing.  I am sure there are many more cases than these to prefer defining explicit routes in WebApiConfig.cs, but at least now you know the consequences of choosing an Attribute-based routing scheme for your ASP.NET Web API Web Applications!



Monday, July 11, 2016

Problem with configuring Swashbuckle/Swagger for ASP.NET Web API

I was configuring Swashbuckle/Swagger for one of my ASP.NET Web API web applications using the standard NuGet package, when I suddenly encountered this error message:



I occasionally also received this error message in Google Chrome:


No matter what I changed in my Web API application, however, my Swagger documentation would not work!

I was never able to come up with a solution for this problem other than blowing away the whole project and starting from scratch, so if you find a solution for this problem, leave your answer in the comments below!

Friday, July 8, 2016

Migrating from ASP.NET Web API to ASP.NET Web API Core

If you are interested in migrating to .NET Core for your ASP.NET Web API application, Microsoft has provided a very nice tutorial on just how to do that:  https://docs.asp.net/en/latest/migration/webapi.html

Overall, the changes from ASP.NET Web API 2.2 to ASP.NET Web API Core are pretty minimal and the revisions make working with ASP.NET Web API considerably cleaner and more understandable than before. 

If  you want to just get started working with ASP.NET Web API Core from scratch, Microsoft provides a handy tutorial for that as well!  https://docs.asp.net/en/latest/tutorials/first-web-api.html