Adding Web API Controller To Existing MVC Project

If you have MVC project and you need to add Web API controller to this project, it can be done very easy.

1. Add Nuget package Microsoft.AspNet.WebApi.Core. This will add references to System.Web.Http.dll.

2. Add registration file for Web API. It would better to do it like Visual Studio does – add file App_Start\WebApiConfig.cs

3. Add using System.Web.Http; to Global.asax.cs

4. Add GlobalConfiguration.Configure(WebApiConfig.Register); in Application_Start() method before registering MVC routes.

Application_Start() would be like this.

5. Create a controller and derive it from System.Web.Http.ApiController

Finding All Controls In ASP.NET Page

When you work with ASP.NET page, you might need to enumerate all controls of a specific type, i.e. text boxes, dropdown list, or table cells. All these controls derive from System.Web.UI.Control class.
To find all controls you need to iterate them recursively from the top one, i.e. Page, or any element that is located on a page (panel, table, etc.). One of the solution is to write an extension method like this.

Also you can use a generic version.

When I need to find all table cells with a specific ID, I can write the following LINQ query:

In C# 6.0 and later you can use Elvis operator in Where clause.

Encrypting appSettings Key In ASP.NET Web.config

I needed a solution to encrypt a single key in appSettings section in ASP.NET Web.config file. The article on MSDN Encrypting and Decrypting Configuration Sections tells about encrypting the whole section but I want to hide only a particular key.
It seems that apsnet_regiis could encrypt only sections, so I’ve found a way how to extract this key to another section and encrypt that section in one of StackOverflow answers http://stackoverflow.com/a/6224769

Here are the steps that must be done to get the result:
1. Add a line in configSections with the name of your new section

2. Add new section under configuration

3. In .NET code get the section and key from it

4. After you deploy your Web application to IIS, you should encrypt section secureAppSettings according to the MSDN article mentioned above. Launch Command Prompt as Administrator (it’s important!) and run command (something like this):

Web API Anonymous Authentication And IIS Express

I’ve been tested a Web API web service and I needed an anonymous authentication. This can be done with attribute [AllowAnonymous].
You can decorate a whole controller

or a particular method(s)

The most curious thing is that it does not work when you run Visual Studio debugger! The secret is hidden in the properties of the Web API project. Click the project in Solution Explorer, then press F4 (don’t choose Properties from context menu). Here you will see authentication settings.

webapi-project-settings

All these properties are saved in .csproj file.

MVC. Placing Javascript Files In View Folder

When you need to split layout and JS code to different files, it might be convenient to place both files in Views/{ControllerName} folder. You need to change web.config file inside Views folder.

1. Add handler in <system.web> section

2. Add handler in <system.webServer> section before BlockViewHandler

Now you can include JavaScript file in your layout page.

Cross-domain Problems in JSON Communication Between ASP.NET Web API 2 and jQuery.ajax()

I had a task to create an ASP.NET web page that should use AJAX request to dynamically update the items of the dropdownlist control SignerDropDownList. I’ve created a javascript function that handles onchange event of the parent dropdownlist. The relevant portion of the script is shown below:

Variable webServiceUrl is a string with URL to web service in MVC format. Just something like “http://host_name:port_number/ws/api/Signer/1”

At first I clear the list of items, then I process the response from the server which comes in the following
JSON format and add items to dropdownlist control.

For the server-side web service I’ve created an Entity Framework model and Web API 2 controller in two projects. The test of the web service from the browser passed.
I successfully publish web service to IIS and assign a port. The test of the ajax call failed due to cross-domain problems.

This problem can be solved very easily by enabling CORS in ASP.NET Web API. All necessary information about that is here

In addition I had to change ajax function on HTML page.

I’ve tested in Google Chrome, everything is OK. But Internet Explorer could not get data from web service. I’ve looked at the Network tab in IE debugger and found that IE did not send any request to web service.

After some time searching in Google I found that JSONP could help to solve this issue. I’ve changed the ajax call and noticed that IE really sent the request. But now it failed due to incorrect format. So I need to change the web service to correctly format the response in JSONP format. This can be done with WebApiContrib.
All information about how to install and use it is located on GitHub here

Beside that we should add a parameter to ajax function to instruct it to make a JSONP call. The final javascript code is listed below:

When I looked at the Netwok tab of IE debugger I saw a request to web sevice.
/ws/api/Signer/1?callback=jQuery1102007129232717448897_1424862016652&_=1424862016653 GET 200 text/javascript 484 B 4.85 s// <![CDATA[
13282 15 4828 16 0 0
// ]]>

So, to organize the AJAX communication between web page and Web API we need an jQuery.ajax() request with relevant paramters on the client side. On the server side we should implement CORS and JSONP support in our web service.