Tag Archives: webapi

C#

Cross-origin resource sharing in ASP.NET Web Api

cors
Often frontend and backend are hosted on different domains. So, you may see error like

  No 'Access-Control-Allow-Origin' header is present on the requested resource.

To allow cross domain requests in your WebApi project you can use next Handler:

using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

namespace App.MessageHandlers
{
    class CorsMessageHandler : DelegatingHandler
    {
        private const string origin = "Origin";
        private const string accessControlRequestMethod = "Access-Control-Request-Method";
        private const string accessControlRequestHeaders = "Access-Control-Request-Headers";
        private const string accessControlAllowOrigin = "Access-Control-Allow-Origin";
        private const string accessControlAllowMethods = "Access-Control-Allow-Methods";
        private const string accessControlAllowHeaders = "Access-Control-Allow-Headers";

        protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var isCorsRequest = request.Headers.Contains(origin);
            var isPreflightRequest = request.Method == HttpMethod.Options;

            if (isCorsRequest)
            {
                if (isPreflightRequest)
                {
                    return Task.Factory.StartNew(() =>
                    {
                        var response = new HttpResponseMessage(HttpStatusCode.OK);
                        response.Headers.Add(accessControlAllowOrigin, request.Headers.GetValues(origin).First());

                        var currentAccessControlRequestMethod = request.Headers.GetValues(accessControlRequestMethod).FirstOrDefault();
                        if (currentAccessControlRequestMethod != null)
                        {
                            response.Headers.Add(accessControlAllowMethods, currentAccessControlRequestMethod);
                        }

                        var requestedHeaders = string.Join(", ", request.Headers.GetValues(accessControlRequestHeaders));
                        if (!string.IsNullOrEmpty(requestedHeaders))
                        {
                            response.Headers.Add(accessControlAllowHeaders, requestedHeaders);
                        }
                        return response;
                    }, cancellationToken);
                }
                else
                {
                    return base.SendAsync(request, cancellationToken).ContinueWith(t =>
                    {
                        var resp = t.Result;
                        resp.Headers.Add(accessControlAllowOrigin, request.Headers.GetValues(origin).First());
                        return resp;
                    });
                }
            }
            else
            {
                return base.SendAsync(request, cancellationToken);
            }
        }
    }
}

And then add it to your config:

GlobalConfiguration.Configuration.MessageHandlers.Add(new CorsMessageHandler());

See also,
Implementing CORS support in ASP.NET Web APIs
CorsHandler.cs

C#

WebClient with automatic decompression in C#

trafcompr
To reduce traffic loading it is often used compression.

You may read scientific investigation about it on
web.mit.edu – Data Compression Techniques for Urban Traffic Data
and more technic on
research.vtu.ac.in – Gateway Traffic Compression.

When you use WebClient in your WebAPI (or etc.) application, downloaded file be in “confused” format. To solve the issue improve web client like this:

using System;
using System.Net;

namespace App
{
    public class WebClientSpecial : WebClient
    {
        protected override WebRequest GetWebRequest(Uri address)
        {
            WebRequest req = base.GetWebRequest(address);
            if (req is HttpWebRequest)
            {
                (req as HttpWebRequest).AutomaticDecompression = 
                  DecompressionMethods.Deflate | DecompressionMethods.GZip;
            }
            return req;
        }
    }
}

The DecompressionMethods in HttpWebRequest can be seen on
http://msdn.microsoft.com/en-us/library/system.net.decompressionmethods%28v=vs.110%29.aspx

C#

Wrap WebAPI RESTful service with Self Host in C#

selfhost
1. Create “Console Application”.
2. Change “.Net Framework Client Profile” to “.Net Framework”!
3. Open “Package Manager Console” and run:

Install-Package Microsoft.AspNet.WebApi.SelfHost -Version 4.0.30506

Version can be removed if you’re using .Net >= 5
4. Add your Models and Controllers to the project.
5. Add code to Main method:

class Program {
  public static void Main(string[] args) {
    var config = new HttpSelfHostConfiguration("http://localhost:8080");

    config.Routes.MapHttpRoute(
        "API Default", "api/{controller}/{id}", 
        new { id = RouteParameter.Optional });

    using (var server = new HttpSelfHostServer(config))
    {
        server.OpenAsync().Wait();
        Console.WriteLine("Press  to quit.");
        Console.ReadLine();
    }
  }
}

6. Run application!

More info,
http://www.asp.net/web-api/overview/hosting-aspnet-web-api/self-host-a-web-api,
http://pfelix.wordpress.com/2012/03/08/asp-net-web-api-self-hosting/