Feb 21, 2016

Editing Visual Studio scaffoldings


Few days back, I was working on an OData project and encountered a problem.

Problem: 
I created an OData application(without MVC) through the default template provided by Visual Studio. Then, I added a Controller using the default scaffolding Web API 2 OData v3 Controller with actions, using Entity Framework. After that, I set up the DB to be accessed by this Controller. 

Then, I checked my OData API for the simplest request(get all records of an entity). It returned HTTP 406 as the response code. I looked up this response code and found as follows:-
"The resource identified by the request is only capable of generating response entities which have content characteristics not acceptable according to the accept headers sent in the request."
W3Org
This means to say that the OData service is returning the response in a format which is not being specified in the Accept header of the request.
I checked all that, passed application/json as Accept header myself, and tried few other things. Nothing worked.


Solution:
Finally, after some googling I found that we just need to replace the using System.Web.Http.OData; with using System.Web.OData; in the controller. That's all.



Fixing the root cause of the problem:
So, I was thinking about this problem and figured that because my scaffolding has this issue, it'll generate an incorrect code every time I add an OData controller. I know it's trivial but why not fix the root cause of the problem.

So, let's see how to edit the scaffolding in Visual Studio 2015. It'll be similar in other versions of VS as well.

1) Following is the existing namespace which is generated with the faulty scaffolding.
2) On my system, I have the following scaffoldings installed for Controllers. I will just fix the OData controller scaffoldings.
3) If you have done default installation for Visual Studio, then the scaffolding folder will reside in the following location(you need to change the Visual Studio version depending on the version installed)
C:\Program Files (x86)\Microsoft Visual Studio 14.0 \Common7\IDE\Extensions\Microsoft\Web\Mvc\Scaffolding\Templates
Here, we can see all the different scaffoldings. I have selected the two scaffoldings that we'll fix now.
4) Inside each folder, we can find scaffoldings corresponding to each language which it can generate.
5) We will go ahead and edit the C# scaffolding. Shown below is the culprit line in the C# scaffolding.
We just update this line from using System.Web.Http.OData; to using System.Web.OData;.
6) Now, the template generates the correct using namespace, as shown below.

So, the next time I create an OData controller, I will not have to worry about getting the wrong using namespace. :)

Hope this help!

3 comments: