Home > WebAPI > Intro to ASP.NET WebAPI

Intro to ASP.NET WebAPI

WebAPI as part of MVC 4 projects template in VS 2012 allows to easily create REST based services. This services use HTTP verbs GET, POST, PUT and DELET for communicating with the server.

This way they can be very easily called from any client in any technology and due to the REST type interface will minimize the number of bytes transmitted.


In addition to this, the server will detect the format of the data, which should be delivered to the client. By default it will be a JSON stream, but its just a mtter of a different header type in the request to change the output to XML.

WebAPI uses a lot of "Convention over Configuration", whichmeans that many default settings are based on naming defaults. Of course all this can be changed, but it’s much easier and better to understand for other people, when following the default conventions.

To create a new WebAPI project, use the MVC 4 template in VS 2012 and the select WebAPI in the following dialog

image image

The project will then already have some setup code like route definition, which is defined in global.asax:

   <pre>public class WebApiApplication : System.Web.HttpApplication 
  protected void Application_Start() 


} </pre>

which will call this function and make sure, that the route pattern /api/{controller} is handled

public static class WebApiConfig
    public static void Register(HttpConfiguration config)
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }


Securing WebAPI using Basic Authentication

Securing any ApiController can be done by adding the [Authorize] attribute from System.Web.Http

To use Basic Authentication the following steps are needed:

Create a new class BasicAuthenticationAttribute:


public class BasicAuthenticationAttribute : System.Web.Http.Filters.ActionFilterAttribute
    public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
        if (actionContext.Request.Headers.Authorization == null)
            actionContext.Response = 
                new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
            string authToken = actionContext.Request.Headers.Authorization.Parameter;
            string decodedToken = Encoding.UTF8.GetString(Convert.FromBase64String(authToken));

            string username = decodedToken.Substring(0, decodedToken.IndexOf(":"));
            string password = decodedToken.Substring(decodedToken.IndexOf(":") + 1);

            if (username == password)
                User user = new User() { UserName = username };

                HttpContext.Current.User = new GenericPrincipal(new ApiIdentity(user), new string[] { });

                actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);


The code above references this ApiIdentity class:

public class ApiIdentity : IIdentity
    public User User { get; private set; }
    public ApiIdentity(User user)
        if (user == null)
            throw new ArgumentNullException("user");

        this.User = user;

    public string Name
        get { return this.User.UserName; }

    public string AuthenticationType
        get { return "Basic"; }

    public bool IsAuthenticated
        get { return true; }


Add the attribute [BasicAuthentication] to the ApiController


Now all calls must provide username and passwort in Basic Auth scheme format.


Example using WebClient:

private void btnGetData_Click(object sender, EventArgs e)
    WebClient wc = new WebClient();

    string username = txtUsername.Text;
    string password = txtPassword.Text;

    wc.Headers.Add("Authorization", "Basic " + 
        Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", username, password))));

    string jsonData = String.Empty;
        jsonData = wc.DownloadString("http://localhost:43153/api/values");
    catch (Exception ex)
        jsonData = "Exception: " + ex.Message;
    txtJSONData.Text = jsonData;



Categories: WebAPI
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: