Monthly Archives: August 2016

Use ExpressJS to Get URL and POST Parameters

GET

// grab the packages we need
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;

// routes will go here

// start the server
app.listen(port);
console.log('Server started! At http://localhost:' + port);
http://example.com/api/users?id=4&token=sdfa3&geo=us
// routes will go here
app.get('/api/users', function(req, res) {
  var user_id = req.param('id');
  var token = req.param('token');
  var geo = req.param('geo');  

  res.send(user_id + ' ' + token + ' ' + geo);
});

POST

npm install body-parser --save
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies

// POST http://localhost:8080/api/users
// parameters sent with 
app.post('/api/users', function(req, res) {
    var user_id = req.body.id;
    var token = req.body.token;
    var geo = req.body.geo;

    res.send(user_id + ' ' + token + ' ' + geo);
});

References
https://scotch.io/tutorials/use-expressjs-to-get-url-and-post-parameters
http://www.tutorialspoint.com/nodejs/nodejs_express_framework.htm
https://www.npmjs.com/package/body-parser-json

Passing multiple POST parameters to Web API Controller Methods

C# :

[HttpPost]
public string PostAlbum(JObject jsonData)
{
    dynamic json = jsonData;
    JObject jalbum = json.Album;
    JObject juser = json.User;
    string token = json.UserToken;

    var album = jalbum.ToObject<Album>();
    var user = juser.ToObject<User>();

    return String.Format("{0} {1} {2}", album.AlbumName, user.Name, token);
}

JavaScript :

var album = {
    AlbumName: "PowerAge",
    Entered: "1/1/1977"
}
var user = {
    Name: "Rick"
}
var userToken = "sekkritt";


$.ajax(
{
    url: "samples/PostAlbum",
    type: "POST",
    contentType: "application/json",
    data: JSON.stringify({ Album: album, User: user, UserToken: userToken }),
     success: function (result) {
        alert(result);
    }
});

How To Get ASP.NET Web API to Return JSON

first remove xml format :

config.Formatters.Remove(config.Formatters.XmlFormatter);

accepts text/html requests and returns application/json responses :

public class BrowserJsonFormatter : JsonMediaTypeFormatter
    {
        public BrowserJsonFormatter()
        {
            this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
            this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("multipart/form-data"));
            this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
            this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/x-www-form-urlencoded"));
            this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));
            this.SerializerSettings.Formatting = Formatting.Indented;
        }

        public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType)
        {
            base.SetDefaultContentHeaders(type, headers, mediaType);
            headers.ContentType = new MediaTypeHeaderValue("application/json");
        }
    }

Register like so:

config.Formatters.Add(new BrowserJsonFormatter());

References
http://stackoverflow.com/questions/9847564/how-do-i-get-asp-net-web-api-to-return-json-instead-of-xml-using-chrome
https://github.com/aspnet/Mvc/issues/1765

Use OWIN to Self-Host ASP.NET Web API and SignalR

Startup.cs

[assembly: OwinStartup(typeof(ERPSelfHostServer.Startup))]
namespace ERPSelfHostServer
{
    public class Startup
    {
        // This code configures Web API. The Startup class is specified as a type
        // parameter in the WebApp.Start method.
        public void Configuration(IAppBuilder appBuilder)
        {
            // Configure Web API for self-host. 
            HttpConfiguration config = new HttpConfiguration();
            config.Formatters.Remove(config.Formatters.XmlFormatter);
            config.Formatters.Add(new BrowserJsonFormatter());

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );


            // Any connection or hub wire up and configuration should go here
            appBuilder.MapSignalR();

            appBuilder.UseWebApi(config);
            
        }
    }
}

Program.cs

static void Main(string[] args)
        {
            // bind to all network interfaces
            //string baseAddress = "http://*:13602/";
            string baseAddress = "http://172.20.63.161:13602";

            using (WebApp.Start<Startup>(baseAddress))
            {
                Thread.Sleep(Timeout.Infinite);
            }
        }

References
http://www.asp.net/web-api/overview/hosting-aspnet-web-api/use-owin-to-self-host-web-api
http://anthonychu.ca/post/web-api-owin-self-host-docker-windows-containers/
http://stackoverflow.com/questions/21634333/hosting-webapi-using-owin-in-a-windows-service
http://stackoverflow.com/questions/20068075/owin-startup-class-missing
http://stackoverflow.com/questions/16642651/self-hosted-owin-and-urlacl