Category Archives: asp.net-web-api

flask route variables 404 not found

I have been trying to get a simple web api to run on my shared hosting environment through 1and1.

I have setup this path ~/myapp/api where i put all my python scripts. This is the one I can't get to work (test.py):

the problem is with the last route. It will only work if I create the directory "tables." otherwise it throws a not found error.

from flask import Flask
app = Flask(__name__) 

@app.route('/myapp/')
def api_base():
  return "/myapp"

@app.route('/myapp/api/')
def api_base_full():
  return "/myapp/api"

@app.route('/myapp/api/table/', methods = ['GET', 'POST'])
def api_routes_table():
    if request.method == 'GET':
        return getAllTableItems()
    elif request.method == 'POST':
        return insertNewTableItem()

.htaccess in ~ directory:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^myapp/(.*)$ /myapp/api/cgitester.py/betabank/$1 [L]

cgiteseter.py:

from wsgiref.handlers import CGIHandler
from test import app

CGIHandler().run(app)

I have a feeling the problem is with my .htaccess file cause I don't really know what i'm doing in there. I can't figure out how to fix this looking at flask documentation and stackoverflow posts. thanks for any help

what i'm trying to do is create a web api so that when I make GET calls to www.example.com/myapp/api/table it returns json of my database. Then www.example.com/myapp/api/table/3 will return table row 3. RIght now i just want it to print some text so I know the right function is getting called.

ApacheBench and Windows Authentication

I'm trying to use the ApacheBench tool in a Windows authenticated, Web Api environment. I am not able to authenticate and get 401 errors. Is it possible to pass Windows credentials using this tool? Including username/password, like below, doesn't work. I really like the simplicity of this tool and will be disappointed if I can't use it in this environment. I'm a Microsoft guy and have no experience in this development realm.

ab -A username:password -c 50 -n 200 -v 2 http://localhost:17325/api/test

Web API on Mono constantly getting 404

I'm currently attempting to run a very simple / basic Web API program on OpenSUSE using mod_mono and apache.

The code executes perfectly on my windows machine when running from visual studio, however once deployed to my OpenSUSE box I get nothing but 404 errors trying to trace down the routes.

I'm sure I'm deploying to the correct directory because the .css file that is auto-generated when creating the solution is on the web server and I can see it when I put in the path.

However, I don't see the Web API splash page when I navigate to the website root in a browser, nor do I see the same XML dump when I type in the path /api/Locations on my Linux server as when I do so in my windows / Visual Studio environment.

I'm assuming I need to do something to make Apache respect my routes file, but I'm simply unsure of what this may be. I also am thinking I may need to adjust how my publish is done (I am currently doing this via FTP right through Visual studio).

I don't even know what I don't know at this point, and would love some help on where to look next. Scouring the web has produced a lot of very old / outdated results that seem to be useless.

http streaming in both directions

Is the following scenario valid for HTTP?

  1. Client sends HTTP header to Server
  2. Server receives header and sends HTTP response header
  3. Client streams HTTP body (chunked transfer)
  4. Server receives request body chunks and sends HTTP response body chunks (again chunked transfer)

I tried implementing this using HttpWebRequest and Asp.Net Web Api but got this error on the client

An unhandled exception of type 'System.NotSupportedException' occurred in System.dll

Additional information: The stream does not support concurrent IO read or write operations

Client

static void Main(string[] args)
{
      HttpWebRequest request = WebRequest.Create("http://localhost.fiddler:16462/") as HttpWebRequest;
      request.SendChunked = true;
      request.ContentType = "application/octet-stream";
      request.Method = "POST";
      request.AllowWriteStreamBuffering = false;
      request.AllowReadStreamBuffering = false;
      request.Timeout = 3600000;

      var requestStream = request.GetRequestStream();
      var responseStream = request.GetResponse().GetResponseStream();
      int bufLength = 10 * 1024;

      byte[] requestBuffer = new byte[bufLength];
      byte[] responseBuffer = new byte[bufLength];

      for (int i = 0; i < 1024; ++i)
      {
          requestStream.Write(requestBuffer, 0, bufLength);
          responseStream.Read(responseBuffer, 0, bufLength);
      }

      requestStream.Close();
      responseStream.Close();
}

I verified that TcpClient does support simultaneous request response streaming. However, it would be nice to see HttpWebRequest also support this.

using System;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace TcpClientTest
{
    class Program
    {
        static void Main(string[] args)
        {
            TcpClient client = new TcpClient("localhost", 16462);
            var stream = client.GetStream();

            byte[] buffer = Encoding.UTF8.GetBytes("POST http://localhost:16462/ HTTP/1.1\r\n");
            stream.Write(buffer, 0, buffer.Length);

            buffer = Encoding.UTF8.GetBytes("Content-Type: application/octet-stream\r\n");
            stream.Write(buffer, 0, buffer.Length);

            buffer = Encoding.UTF8.GetBytes("Host: localhost:16462\r\n");
            stream.Write(buffer, 0, buffer.Length);

            buffer = Encoding.UTF8.GetBytes("Transfer-Encoding: chunked\r\n\r\n");
            stream.Write(buffer, 0, buffer.Length);

            int chunkLen = 128 * 1024;
            string chunkSizeStr = chunkLen.ToString("X");
            byte[] chunkSizeBytes = Encoding.UTF8.GetBytes(chunkSizeStr + "\r\n");
            buffer = new byte[chunkLen];
            for (int i = 0; i < chunkLen; ++i)
            {
                buffer[i] = (byte)'a';
            }

            // Start reader thread
            var reader = new Thread(() =>
            {
                byte[] response = new byte[128 * 1024];
                int bytesRead = 0;
                while ((bytesRead = stream.Read(response, 0, response.Length)) > 0)
                {
                    Console.WriteLine("Read {0} bytes", bytesRead);
                }
            });

            reader.Start();

            // Streaming chunks
            for (int i = 0; i < 1024 * 1024; ++i)
            {
                stream.Write(chunkSizeBytes, 0, chunkSizeBytes.Length);
                stream.Write(buffer, 0, buffer.Length);
                stream.Write(Encoding.UTF8.GetBytes("\r\n"), 0, 2);
            }

            buffer = Encoding.UTF8.GetBytes("0\r\n\r\n");
            stream.Write(buffer, 0, buffer.Length);
            reader.Join();
        }
    }
}

Are there any disadvantages in adding a .net webapi infront of localhost services

Right now I have a few services running on localhost with Apache and some python bindnings on different ports.

Since my area of expertise is in .net an webapi I am considering to add a webapi project infront of thse and do authorization in webapi instead of having to add stuff to apache. Aswell as map different routes to same localhost endpoint.

My question is then, is this a common practise to do such, is there any obvious downfalls that I should consider before doings this. Webapi being configured on IIS, should I expect latency for IIS calling localhost - as are there anything that makes localhost slower to respond than normal endpoints.

Reason for not using apache is that since I am on windows and experienced with IIS/.Net, the cost of fixng something that goes wrong or adding new stuff to apache is higher than sticking to what i know.

call web api from mono ubuntu gives an internal server error

I have an web-api on mono on Ubuntu

then I tried to call it from another website on the same machine

by this way

HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("http://127.0.0.1:8084/");
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            //   {"isCluster":"true","user_password":null,"sname":null,"uname":null,"value":null,"type":"","domain_guid":""}
            // string postBody = "{id:"+id+", test:"+test+", pass:"+pass+", type:"+type+", guid:"+guid+"}";
            string postBody = JsonConvert.SerializeObject(request);

            HttpContent content = new StringContent(postBody, Encoding.UTF8, "application/json");
            try{
                HttpResponseMessage response = client.PostAsync("api/streamsie/test_api", content).Result;

                if (response.IsSuccessStatusCode)
                {
                    // Read the response body as string
                    string json = response.Content.ReadAsStringAsync().Result;

                    // deserialize the JSON response returned from the Web API back to a login_info object
                    return JsonConvert.DeserializeObject<string>(json);
                } 

I always get my responce as

response    {StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
 {
 Date: Wed, 19 Nov 2014 13:02:39 GMT
 Server: Mono.WebServer.XSP/3.8.0.0 Linux
 Connection: close
 X-AspNet-Version: 4.0.30319
 Cache-Control: private
 Content-Length: 4592
 Content-Type: text/html
 }} System.Net.Http.HttpResponseMessage

please help

Note : when I use the same method to call the same api from windows server it works fine

also note that my apche file apache2.conf is as

# This is the main Apache server configuration file.  It contains the
# configuration directives that give the server its instructions.
# See http://httpd.apache.org/docs/2.4/ for detailed information about
# the directives and /usr/share/doc/apache2/README.Debian about Debian specific
# hints.
#
#
# Summary of how the Apache 2 configuration works in Debian:
# The Apache 2 web server configuration in Debian is quite different to
# upstream's suggested way to configure the web server. This is because Debian's
# default Apache2 installation attempts to make adding and removing modules,
# virtual hosts, and extra configuration directives as flexible as possible, in
# order to make automating the changes and administering the server as easy as
# possible.

# It is split into several files forming the configuration hierarchy outlined
# below, all located in the /etc/apache2/ directory:
#
#   /etc/apache2/
#   |-- apache2.conf
#   |   `--  ports.conf
#   |-- mods-enabled
#   |   |-- *.load
#   |   `-- *.conf
#   |-- conf-enabled
#   |   `-- *.conf
#   `-- sites-enabled
#       `-- *.conf
#
#
# * apache2.conf is the main configuration file (this file). It puts the pieces
#   together by including all remaining configuration files when starting up the
#   web server.
#
# * ports.conf is always included from the main configuration file. It is
#   supposed to determine listening ports for incoming connections which can be
#   customized anytime.
#
# * Configuration files in the mods-enabled/, conf-enabled/ and sites-enabled/
#   directories contain particular configuration snippets which manage modules,
#   global configuration fragments, or virtual host configurations,
#   respectively.
#
#   They are activated by symlinking available configuration files from their
#   respective *-available/ counterparts. These should be managed by using our
#   helpers a2enmod/a2dismod, a2ensite/a2dissite and a2enconf/a2disconf. See
#   their respective man pages for detailed information.
#
# * The binary is called apache2. Due to the use of environment variables, in
#   the default configuration, apache2 needs to be started/stopped with
#   /etc/init.d/apache2 or apache2ctl. Calling /usr/bin/apache2 directly will not
#   work with the default configuration.


# Global configuration
#

#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# NOTE!  If you intend to place this on an NFS (or otherwise network)
# mounted filesystem then please read the Mutex documentation (available
# at <URL:http://httpd.apache.org/docs/2.4/mod/core.html#mutex>);
# you will save yourself a lot of trouble.
#
# Do NOT add a slash at the end of the directory path.
#
#ServerRoot "/etc/apache2"

#
# The accept serialization lock file MUST BE STORED ON A LOCAL DISK.
#
Mutex file:${APACHE_LOCK_DIR} default

#
# PidFile: The file in which the server should record its process
# identification number when it starts.
# This needs to be set in /etc/apache2/envvars
#
PidFile ${APACHE_PID_FILE}

#
# Timeout: The number of seconds before receives and sends time out.
#
Timeout 300

#
# KeepAlive: Whether or not to allow persistent connections (more than
# one request per connection). Set to "Off" to deactivate.
#
KeepAlive On

#
# MaxKeepAliveRequests: The maximum number of requests to allow
# during a persistent connection. Set to 0 to allow an unlimited amount.
# We recommend you leave this number high, for maximum performance.
#
MaxKeepAliveRequests 100

#
# KeepAliveTimeout: Number of seconds to wait for the next request from the
# same client on the same connection.
#
KeepAliveTimeout 5


# These need to be set in /etc/apache2/envvars
User ${APACHE_RUN_USER}
Group ${APACHE_RUN_GROUP}

#
# HostnameLookups: Log the names of clients or just their IP addresses
# e.g., www.apache.org (on) or 204.62.129.132 (off).
# The default is off because it'd be overall better for the net if people
# had to knowingly turn this feature on, since enabling it means that
# each client request will result in AT LEAST one lookup request to the
# nameserver.
#
HostnameLookups Off

# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here.  If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
ErrorLog ${APACHE_LOG_DIR}/error.log

#
# LogLevel: Control the severity of messages logged to the error_log.
# Available values: trace8, ..., trace1, debug, info, notice, warn,
# error, crit, alert, emerg.
# It is also possible to configure the log level for particular modules, e.g.
# "LogLevel info ssl:warn"
#
LogLevel warn

# Include module configuration:
IncludeOptional mods-enabled/*.load
IncludeOptional mods-enabled/*.conf

# Include list of ports to listen on
Include ports.conf


# Sets the default security model of the Apache2 HTTPD server. It does
# not allow access to the root filesystem outside of /usr/share and /var/www.
# The former is used by web applications packaged in Debian,
# the latter may be used for local directories served by the web server. If
# your system is serving content from a sub-directory in /srv you must allow
# access here, or in any related virtual host.
<Directory />
    Options FollowSymLinks
    AllowOverride None
    Require all denied
</Directory>

<Directory /usr/share>
    AllowOverride None
    Require all granted
</Directory>

<Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

#<Directory /srv/>
#   Options Indexes FollowSymLinks
#   AllowOverride None
#   Require all granted
#</Directory>




# AccessFileName: The name of the file to look for in each directory
# for additional configuration directives.  See also the AllowOverride
# directive.
#
AccessFileName .htaccess

#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<FilesMatch "^\.ht">
    Require all denied
</FilesMatch>


#
# The following directives define some format nicknames for use with
# a CustomLog directive.
#
# These deviate from the Common Log Format definitions in that they use %O
# (the actual bytes sent including headers) instead of %b (the size of the
# requested file), because the latter makes it impossible to detect partial
# requests.
#
# Note that the use of %{X-Forwarded-For}i instead of %h is not recommended.
# Use mod_remoteip instead.
#
LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %O" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent

# Include of directories ignores editors' and dpkg's backup files,
# see README.Debian for details.

# Include generic snippets of statements
IncludeOptional conf-enabled/*.conf

# Include the virtual host configurations:
IncludeOptional sites-enabled/*.conf

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet