Archive

Archive for October, 2012

Intro to ASP.NET WebAPI

October 7, 2012 Leave a comment

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() 
  { 
    AreaRegistration.RegisterAllAreas(); 

    WebApiConfig.Register(GlobalConfiguration.Configuration); 

    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
    RouteConfig.RegisterRoutes(RouteTable.Routes); 
    BundleConfig.RegisterBundles(BundleTable.Bundles); 
  } 
} </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)
    {
        config.Routes.MapHttpRoute(
            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);
        }
        else
        {
            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[] { });

                base.OnActionExecuting(actionContext);
            }
            else
            {
                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;
    try
    {
        jsonData = wc.DownloadString("http://localhost:43153/api/values");
    }
    catch (Exception ex)
    {
        jsonData = "Exception: " + ex.Message;
    }
    txtJSONData.Text = jsonData;

}

 .

Categories: WebAPI

Tracing HTTP with Fiddler

October 6, 2012 Leave a comment

Fiddler is a great tool for debugging HTTP traffic between a HTTP client and a HTTP server.

It’s free and can be downloaded from here: http://www.fiddler2.com

Debugging with localhost

Fiddler is acting as a local proxy and enables itself for all WinInet based communication after startup.

However, there are some things to remember when debugging traffic to and from a local server, because depending on the .NET framework version, proxy usage is disabled in code.

Example: The traffic from this site should be captured: http://localhost/MySite/MyPage.aspx

There are a few workarounds, which should help to solve this situation:

– Use <machinename> instead of localhost ==> http://mymachine/MySite/MyPage.aspx

– Use ipv4.fiddler instead of localhost ==> http://ipv4.fiddler/MySite/MyPage.aspx

– Use ipv6.fiddler instead of localhost ==> http://ipv4.fiddler/MySite/MyPage.aspx

Debugging with IIS 8 Express on Windows 8

There can be even more problems, when using IIS 8 Express on Windows 8.

IIS Express is hardcoded to respond only to requests on localhost.

Therefore ipv4.fiddler does not work in this scenario.

But also this scenario can be solved:

– Use localhost.fiddler instead of localhost ==> http://localhost.fiddler:5057/MySite/MyPage.aspx

 

Debugging Http traffic to and from immersive / New UI Style apps

Example: When using the new immersive IE, there must be done one more change, because all Win 8 New UI Style apps cannot contact local services by default.

This will work only, if they get an additional server capability, but much better for debugging is to set the app on the excempt list.

Fiddler can help to do this:

image image

This way also the immersive IE browser and every other Windows Store App is able to contact local services via HTTP.

Categories: Debugging, Windows 8