GithubHelp home page GithubHelp logo

unosquare / embedio Goto Github PK

View Code? Open in Web Editor NEW
1.4K 64.0 171.0 14.13 MB

A tiny, cross-platform, module based web server for .NET

Home Page: http://unosquare.github.io/embedio

License: Other

C# 84.33% HTML 0.88% JavaScript 13.51% CSS 1.28%
mono webserver websocket dotnet dotnetcore websockets url-segment tiny routing-strategies embedded

embedio's People

Contributors

alhimik45 avatar benny856694 avatar bufferunderrun avatar chyyran avatar dependabot-preview[bot] avatar desistud avatar duddo avatar edmundormz avatar geoperez avatar greciaveronica avatar israelramosm avatar jpalcala avatar jtol84 avatar k3z0 avatar kadosh avatar kuyoska avatar lwalejko avatar marcolpr avatar marcuswichelmann avatar mariodivece avatar marner2 avatar perkio avatar rdeago avatar scobie avatar serk352 avatar splamy avatar srad avatar thomaspiskol avatar unknown6656 avatar vbhavsar-alchemysystems avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

embedio's Issues

Non en_US locale can cause ArgumentException on any request.

I got ArgumentException with any http request, the stack trace is:

2015-11-27 16:08:16.704 System.ArgumentException: 지정한 값에 잘못된 제어 문자가 있습니다.
매개 변수 이름: value
위치: System.Net.WebHeaderCollection.CheckBadChars(String name, Boolean isHeaderValue)
위치: System.Net.WebHeaderCollection.SetInternal(String name, String value)
위치: Unosquare.Labs.EmbedIO.Extensions.NoCache(HttpListenerContext context)
위치: Unosquare.Labs.EmbedIO.Modules.WebApiModule.<.ctor>b__2_0(WebServer server, HttpListenerContext context)
위치: Unosquare.Labs.EmbedIO.WebServer.ProcessRequest(HttpListenerContext context)

The cause is

    context.Response.AddHeader(Constants.HeaderLastModified,
            DateTime.UtcNow.ToString(Constants.BrowserTimeFormat));

in Extensions.NoCache() method.

With Korean locale, ToString("ddd, dd MMM yyyy HH:mm:ss 'GMT'") generates non-ASCII characters.
The token "ddd" is the problem.

Workaround: change the locale on program startup, like

var culture = CultureInfo.CreateSpecificCulture("en-US");
CultureInfo.DefaultThreadCurrentCulture = culture;
CultureInfo.DefaultThreadCurrentUICulture = culture;

I wish this problem is fixed for non-english users in the world~ :)

Update NuGet Package

Self-explanatory. I realized the NuGet Package is not up to date because the RunAsyc method does not return a task but in the code it does.

Add PCL Compatibility for Custom Modules

Hey again,
Unfortunately, because of using System.Net.HttpListenerContext in "ResponseHandler" delegate for new 'Map's it is now impossible to write custom and also portable modules for the WebServer.

We should probably contain that class in a local type so we can access it.

WebSockets Support on Windows 7 and Mono 3.x

Hi,

It's not an issue or pr, just asking question. As i don't know how to contact you (a mailing list ?) let's do this here. Feel free to delete if it is not appropriate.

Before Embedio, i used the websocket-sharp project to serve websocket in my app. Yesterday, i've just understood that the WebsocketModule provide by Embebio is using the Microsoft http.sys and so, starts with Windows 8 and higher. Little punch in my face as my dev env is always in Win7 (yes, i hate the win8&10 UI) and my app have to support Win7.

According to https://msdn.microsoft.com/fr-fr/library/system.net.websockets.websocket

The classes and class elements in the N:System.Net.WebSockets namespace that are supported on Windows 7, Windows Vista SP2, and Windows Server 2008 are abstract classes. This allows an application developer to inherit and extend these abstract classes with an actual implementation of client WebSockets.

Do you known if it exists an implementation of this class or at least, if the websocket-sharp can be integrated in Embedio with little effort to support websocket for Win7 ?

Thanks for your answer.

Fix Samples Solution

Currently the Samples solution looks bad and it is kind of broken. Please fix.

Websocket error 404

It throws 404 when trying to access web socket examples.

2015-11-08 06:05:07,838 [12] ERROR Unosquare.Labs.EmbedIO.Samples.Program No module generated a response. Sending 404 - Not Found

Strong Name the nuget assembly

Can the nuget package be updated to contain a strong named assembly, please? My main code needs to be strong named and therefore this is a blocker for me to use the embedio lib.

Samples not running on NETFX 4.5.2/4.6 - Missing sqlite3

An unhandled exception of type 'System.DllNotFoundException' occurred in Microsoft.Data.Sqlite.dll

Additional information: Unable to load DLL 'sqlite3': The specified module could not be found. (Exception from HRESULT: 0x8007007E)

Allow for sessions cookies to be 'root only'

The session module will create session cookies whenever it finds no matching cookie for the requested path.
These cookies will e create for the path that has been requested.
e.g. If the request is for http://www.sample.com/foo/bar the cookie path will be something like '/foo/bar'.

This behaviour can lead to a single use having multiple vaild session cookies at once.

If a user has no valid cookie for a site and requests the path '/foo/bar', a cookie for that path will be created.
If the user then requests the path '/bar/foo', another cookie will be created, since the path of the previous one does not match.

Maintaining sessions is quite a task with mutliple sessions per path per user.

To solve issues like this, cookies can be created for the root path of a server exclusively.
This way a user will get a single cookie that is valid for the whole domain.

I'd therefore suggest to add an UseRootPathOnly property to the session module:
In ISessionWebModule.cs after line 56 insert:

bool UseRootPathOnly { get; set; }

In LocalSessionModule.cs after line 192 insert:

public bool UseRootPathOnly { get; set; }

In LocalSessionModule.cs replace line 37 with:

var sessionCookie = (UseRootPathOnly ? new Cookie(SessionCookieName, sessionId, "/") : new Cookie(SessionCookieName, sessionId));

or

Cookie sessionCookie;
if(UseRootPathOnly)
  sessionCookie = new Cookie(SessionCookieName, sessionId, "/");
else
  sessionCookie = new Cookie(SessionCookieName, sessionId);

Upgrade error to embedio v1.2.5 with nuget

Hi,

I can't upgrade to the last v1.2.5 release from nuget due to a dependency error :

Attempting to resolve dependency 'Newtonsoft.Json (≥ 9.0.1)'.
'EmbedIO' already has a dependency defined for 'System.Security.Cryptography.Primitives'.

The regression seems to have been introduced in the commit 0e333d0?diff=split

support nullable parameter in the regexp engine

Hi,

my goal is to support optional parameter by the new regexp routing engine. With this
patch, you can now declare a nullable parameter :

            [WebApiHandler(HttpVerbs.Get, RelativePath + "people/{id}")]
            public bool GetPeople(WebServer server, HttpListenerContext context, int? id)
            {
                // when GET /people/, id will be forced to null and not throwing exception
                if (id == null) {
                    return context.JsonResponse(People.All());
                }

                // else use the actual parsing and cast the int to id.
                else  {
                    return context.JsonResponse(People.FirstOrDefault(p => p.Key == id));
                }
            }

It works but has some limits :

  1. when GET /people the regexp doesn't match the right url due to the fact that NormalizeRegexPath() doesn't know if a param is optional (nullable) and slash need to be ignored..
  2. only the last nullable parameter is supported, same case as (1).

Problem with MVC application

I have a mvc website and i would like to embed it with embedio...
I tried above code but no luck.

screenshot_4

Unosquare.Labs.EmbedIO.WebServer server = new Unosquare.Labs.EmbedIO.WebServer(port, new Unosquare.Labs.EmbedIO.Log.SimpleConsoleLog());
server.RegisterModule(new Unosquare.Labs.EmbedIO.Modules.LocalSessionModule());
server.RegisterModule(new Unosquare.Labs.EmbedIO.Modules.StaticFilesModule(path));
server.Module<Unosquare.Labs.EmbedIO.Modules.StaticFilesModule>().UseRamCache = true;
server.RunAsync();

embedio set read lock in static files

Hi,

I don't know if it's a bug or a feature but since i upgrade from v1.0.17 to v1.1.0, the statics files served by embedio are read lock.

In the past version, i used to modify html, css or js file while embedio were working and just refresh browser to view result. Now, it's not possible due to some lock set by embedio. I'm forced to rexec the process and then refresh browser which is a killer workflow.

Random port selection demo

I just wanted to share with you a random port choosing demo that I created for myself. Perhaps you will want to build this feature into your project one day, but the example below is working fine for me and it may serve as a helpful example for other readers.

The wrapper class (StaticWebServer) is shown last. Here is how I now use it from my WinForms demo:

[STAThread]
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);

    using (var webServer = new StaticWebServer())
    {
        webServer.RunAsync();
        Application.Run(new Views.MainView(webServer.UsingBaseAddress));
    }
}

...and in the main view:

public MainView(string webViewUrl = "about:blank")
{
    InitializeComponent();
    browser.Url = new Uri(webViewUrl);
    mainStatusLabel.Text = "";
}

And finally, here is the StaticWebServer class, which chooses the port to use dynamically:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Unosquare.Labs.EmbedIO;
using Unosquare.Labs.EmbedIO.Log;
using Unosquare.Labs.EmbedIO.Modules;

namespace YourOwnNamespace
{
    class StaticWebServer : IDisposable
    {
        public StaticWebServer() { }

        static Random _portGenerator = new Random();
        static List<int> _portsUsed = new List<int>();

        /// <summary>
        /// An instance of the (awesome!) EmbedIO WebServer.
        /// </summary>
        WebServer _server;

        /// <summary>
        /// String format template to merge the randomly generated port into.
        /// Default: "http://127.0.0.1:{0}/"
        /// </summary>
        public string BaseAddressTemplate { get; set; } = "http://127.0.0.1:{0}/";
        public int PortRangeMin { get; set; } = 51001;
        public int PortRangeMax { get; set; } = 65001;
        /// <summary>
        /// Relative or absolute path to serve static files from.
        /// </summary>
        public string RootFilesystemPath { get; set; } = "browse";

        /// <summary>
        /// The base address currently being used by the server.
        /// </summary>
        public string UsingBaseAddress { get; private set; }
        /// <summary>
        /// The port currently being used by the server.
        /// </summary>
        public int UsingPort { get; private set; }
        /// <summary>
        /// The root filesystem path currently being used by the server.
        /// </summary>
        public string UsingRootFilesystemPath { get; private set; }

        WebServer CreateServer(string baseAddress, string rootPath)
        {
            var logger = new DebugLogger();
            var server = new WebServer(baseAddress, logger);

            var headers = new Dictionary<string, string>()
            {
#if DEBUG
                // The following is mostly useful for debugging.
                { Constants.HeaderCacheControl, "no-cache, no-store, must-revalidate" },
                { Constants.HeaderPragma, "no-cache" },
                { Constants.HeaderExpires, "0" }
#endif
            };

            var staticFileMod = new StaticFilesModule(rootPath, headers);
            staticFileMod.DefaultExtension = ".html";
            server.RegisterModule(staticFileMod);

            return server;
        }

        string GetAbsoluteRootDirectoryPath()
        {
            if (Path.IsPathRooted(RootFilesystemPath))
                return RootFilesystemPath;
            var baseDir = Path.GetDirectoryName(
                System.Reflection.Assembly.GetEntryAssembly()
                .Location);
            return Path.Combine(baseDir, RootFilesystemPath);
        }

        public void RunAsync()
        {
            UsingRootFilesystemPath = GetAbsoluteRootDirectoryPath();
            Debug.Print("Serving static files from: {0}", UsingRootFilesystemPath);

            // Random port selection adapted from http://stackoverflow.com/a/223188/16387
            UsingPort = -1;
            UsingBaseAddress = null;
            while (true)
            {
                UsingPort = _portGenerator.Next(PortRangeMin, PortRangeMax);
                if (_portsUsed.Contains(UsingPort))
                    continue;

                UsingBaseAddress = String.Format(BaseAddressTemplate, UsingPort.ToString());
                _server = CreateServer(UsingBaseAddress, UsingRootFilesystemPath);
                try
                {
                    _server.RunAsync();
                } catch (System.Net.HttpListenerException)
                {
                    _server.Dispose();
                    _server = null;
                    continue;
                }
                _portsUsed.Add(UsingPort);
                break;
            }
        }

        public void Dispose()
        {
            Dispose(true);
        }

        void Dispose(bool disposing)
        {
            if (!disposing)
                return;

            var server = _server;
            _server = null;

            if (server == null)
                return;
            server.Dispose();
        }

        #region DebugLogger

        /// <summary>
        /// Provides a simple logger for Debug output.
        /// </summary>
        class DebugLogger : ILog
        {
            private static void WriteLine(string format, params object[] args)
            {
                var d = DateTime.Now;
                var dateTimeString = string.Format("{0}-{1}-{2} {3}:{4}:{5}.{6}",
                    d.Year.ToString("0000"), d.Month.ToString("00"), d.Day.ToString("00"), d.Hour.ToString("00"),
                    d.Minute.ToString("00"), d.Second.ToString("00"), d.Millisecond.ToString("000"));

                format = dateTimeString + "\t" + format;

                if (args != null)
                    Debug.Print(format, args);
                else
                    Debug.Print(format);
            }

            public virtual void Info(object message)
            {
                InfoFormat(message.ToString(), null);
            }

            public virtual void Error(object message)
            {
                ErrorFormat(message.ToString(), null);
            }

            public virtual void Error(object message, Exception exception)
            {
                ErrorFormat(message.ToString(), null);
                ErrorFormat(exception.ToString(), null);
            }

            public virtual void InfoFormat(string format, params object[] args)
            {
                WriteLine(format, args);
            }

            public virtual void WarnFormat(string format, params object[] args)
            {
                WriteLine(format, args);
            }

            public virtual void ErrorFormat(string format, params object[] args)
            {
                WriteLine(format, args);
            }

            public virtual void DebugFormat(string format, params object[] args)
            {
                WriteLine(format, args);
            }
        }

        #endregion
    }
}

Including source to project leads StaticFilesModules HttpListenerException when serving static file

When I use the nuget package everything is fine, but when I use the source and add it to my project I get the following exception service a static file, but it still works:

System.Net.HttpListenerException ist aufgetreten.
  HResult=-2147467259
  Message=Der E/A-Vorgang wurde wegen eines Threadendes oder einer Anwendungsanforderung abgebrochen
(The I/O process was canceled because of a thread ending or an application request)
  Source=System
  ErrorCode=995
  NativeErrorCode=995
  StackTrace:
       bei System.Net.HttpResponseStream.Write(Byte[] buffer, Int32 offset, Int32 size)
       bei Unosquare.Labs.EmbedIO.Modules.StaticFilesModule.HandleGet(HttpListenerContext context, WebServer server, Boolean sendBuffer) in c:\...\embedio\Unosquare.Labs.EmbedIO\Modules\StaticFilesModule.cs:Zeile 277.
  InnerException:

2015-05-12_19h20_44

I have 3 Projects now:

  1. embedio Checkout
  2. WebService (adds embedio)
  3. My App (adds WebService)

I'm adding the controllers via a anonymous function, could that be the issue?, Pseudocode:

public WebWorker(Action<WebServer> doStuff = null)
{
    this.doStuff = doStuff;
    ...
}

...

private void DoWorkHandler(object sender, DoWorkEventArgs e)
{
    using (var server = new WebServer(Url))
    {
        server.RegisterModule(new StaticFilesModule(e.Argument.ToString()));
        server.RegisterModule(new WebApiModule());

        if (doStuff != null)
        {
            doStuff(server);
        }
    ...
}

In the App:

...
WebWorker = new WebService.WebWorker((Unosquare.Labs.EmbedIO.WebServer server) =>
    {
        server.Module<Unosquare.Labs.EmbedIO.Modules.WebApiModule>().RegisterController<Controller.StorageController>();
        server.Module<Unosquare.Labs.EmbedIO.Modules.WebApiModule>().RegisterController<Controller.LogController>();
    });
...

Any idea?

SimpleConsoleLogger not asynchronous

The SimpleConsoleLogger is completely synchronous. The calls to the console are degrading the performance of the request-response cycles. Pick a thread from the thread pool and use a ConcurrentQueue (https://msdn.microsoft.com/en-us/library/dd267265%28v=vs.110%29.aspx) or use other means such as a BlockingCollection as described here (http://stackoverflow.com/questions/3670057/does-console-writeline-block)

Please note that the above StackOverflow answer is not using a ThredPool Thread. Use a Thread Pool Thread instead.

Incorrect handling when URL does not contain a trailing slash.

I configured a basic static server to test EmbedIO and I found that certain pages would not load depending on if the URL contained a trailing slash or not.

For instance, assume that I'm serving files from C:\temp\ and that C:\temp\xyz\ is a subfolder that exists with an index.html file inside of it.

If I have a link that points to href="/xyz/" the page loads. However, if the link points to href="/xyz" then a 404 error is returned.

Escaping issue in Extension.RequestFormData()

Hi,

i've found a error in the way Extension.RequestFormData() is escaping characters, in particular the "plus" sign.

In one of my forms, i use an ajax call with jQuery to send data to a RestApi Controller. When jQuery calls $form.serialize(), it encodes space as "plus" sign. Example : field1=value1withoutspace&field2=value2+with+spaces.

The problem is that the Uri.UnescapeDataString() do not correctly handle the "plus" sign as a space but as a "plus" sign... You can see more details to blog msdn or rick strahl blog.

A workaround consist of using WebUtility.UrlDecode and so you can see a proposal patch below.

--- C:\www\embedio-master\Unosquare.Labs.EmbedIO\Extensions.cs.
+++ C:\www\embedio-master\Unosquare.Labs.EmbedIO\Extensions.cs
@@ -281,7 +281,7 @@

                     return stringData.Split('&')
                         .ToDictionary(c => c.Split('=')[0],
-                            c => Uri.UnescapeDataString(c.Split('=')[1]));
+                            c => WebUtility.UrlDecode(c.Split('=')[1]));
                 }
             }
         }

Thanks,

Not able to set NullLog!

I did install from NuGet (1.4.6).
In this binary, there's no way to set NullLog as ILog in Webserver constructor.
Looking at the source code, you're using conditional tag for compilation.
Is there any reason for that?
Is it safe just download all source code and set COMPAT in "Conditional compilation symbols" at build properties?

staticfilemodule: possible invalid char exception

Cause:
the call to " context.Response.AddHeader(Constants.HeaderLastModified, utcFileDateString);" will trigger invalid char exception if running on non-english locale, since 'utcFileDataString' possibly has invalid chars (Chinese character in my case).

Possible fix:
var utcFileDateString = fileDate.ToUniversalTime().ToString(Constants.BrowserTimeFormat, CultureInfo.InvariantCulture) - add InvariantCulture to the format function.

Thanks for the great project.

Rename RegEx to Regex

The more common term is Regex rather than RegEx. Please rename these in the source, readme, documentation, and samples. Thanks and sorry for causing the extra work.

Windows 8.1 Store App

Hey,
It seems that unfortunately HTPPListener is not supported on Windows 8.1 Store Apps. And no 'Capability' can solve the problem. However, I believe that socket listening is available on Windows 8.1 Store Apps tho using StreamSocketListener class. I think this is true for Windows Phone as well.

So next to .Net Core, we need to have an HTTPListener port for Windows 8.1 Store Apps, Windows 8.1 Phone Apps and Windows 8 Phone Apps.

Implement Deep Object Parsing for ParseFormData Extension Method

I'm using a bootstrap-select2 to support ajax tagging on my webapp.
The underlying html is
<select name="tags" multiple="multiple"></select>

When form is submitted, browser send multiple values for the same input name.
The exception is thrown by ParseFormData() which is a Dictionary<string, string>.

Do you plan to support multiple values ?

Thanks

Implement DeleteSession method in LocalSessionModule

Hi,

I am facing an issue (not really a bug) with the LocalSessionModule and i will trying to explain clearly, not easy.

  1. When a user connects to my app (ie: index.html), Embedio always starts a session (in memory) and so a cookie "__session" is created in his browser. No problem.
  2. Then, the user login and i add some extras infos to check security (roles based) to the embedio session (session.Data.TryAdd("user-roles", new List<String>() { "admin", "debug" })). No problem.
  3. At the end, the user logout and because there is no "DeleteSesssion()" method, i simply delete all extras infos i've added with session.Data.Clear(). The session in Embedio is always enabled but do no rely on extras infos i used to check securty (this user is not admin anymore). A new session is started for the user, new session in Embedio and the browser get a new "__session" AND the old one. No problem.
  4. BUT, when the user refresh his browser, the 2 "__session" cookies are send (";" separed) and Embedio take the first valid, the old one because always in memory and not the new...

Could you add a new method DeleteSession(SessionInfo session) in the LocalSessionModule to properly delete a session in embedio ?

Thanks.

Async Controller Actions

Since the controller actions are not tasks I wonder if you have another general notion on how to wait for I/O code in actions to complete?

Currently I'm using task.wait() for a task to complete, which doesn't seem to be 100% working, I need to debug a few cases yet. However, can I declare actions as Tasks?

Large static file cause 'Out Of Memory' error

I just use this project for servering a large archive(1.2GB), but it raises an 'Out Of Memory' error.

500 - Internal Server Error
Message

Failing module name: Static Files Module
System.OutOfMemoryException

Stack Trace

     System.IO.File.InternalReadAllBytes(String path, Boolean checkHost)
     Unosquare.Labs.EmbedIO.Modules.StaticFilesModule.HandleGet(HttpListenerContext context, WebServer server, Boolean sendBuffer)  C:\Unosquare\embedio\Unosquare.Labs.EmbedIO\Modules\StaticFilesModule.cs: 281
     Unosquare.Labs.EmbedIO.Modules.StaticFilesModule.<.ctor>b__37_1(WebServer server, HttpListenerContext context)  C:\Unosquare\embedio\Unosquare.Labs.EmbedIO\Modules\StaticFilesModule.cs: 187
     Unosquare.Labs.EmbedIO.WebServer.ProcessRequest(HttpListenerContext context)  C:\Unosquare\embedio\Unosquare.Labs.EmbedIO\WebServer.cs: 351

how can i solve it?

Tasks not handled correctly

I suggest you guys read this blog and change WebServer.RunAsync accordingly: http://blog.stephencleary.com/2014/05/a-tour-of-task-part-1-constructors.html

  • Use Task.Run instead of Task.Factory.StartNew, the latter shouldn't be used hardly ever
  • Support cancellation better
    • currently inelegantly handled via clientSocketTask.Wait(ct)
    • pass a CancellationTokenSource argument instead of CancellationToken
    • Check source.Token.IsCancellationRequested inside the while loop
    • Catch/throw OperationCanceledException instead of AggregateException
      *1 Use async/await if .NET 4.5 is present, allowing your RunAsync method to work concurrently as well as in parallel

We are the same developers that gave you the support initially (@marner2, @faeriedust, @Joe0), but we ourselves found out over time we were not doing it right either.

Support file upload

Hi,

Do you have a code snippet to handle file uploading from a html form <input type="file" /> ?

Thanks,

StaticFilesModule - Check for byte range requests before reading the entire file

Line 251, by the time the check for byte range requests is performed, the entire file has already been read which could potentially be a very large file. Byte range requests should not use RAM caches either. Additionally, the response must contain a 206 Partial content header.

Make sure you use a FileStream with shared read access so the file is not locked when it is being read.

Basic example doesn't serve static files

I just installed the nuget package and created a simple index.html file an placed it under c:/web/index.html and used the first code example to get the index.html served within the web browser (which automatically opens given the demo code) and it fails because the server is not reachable.

Could you try if the code is actually working, or is anything else required here?

Failing Local Session Module because of KeyNotFoundException

I keep seeing the following error.

Failing module name: Local Session Module
The given key was not present in the dictionary.

Stack Trace:

System.Collections.Generic.KeyNotFoundException: The given key was not present in the dictionary.
   at System.Collections.Concurrent.ConcurrentDictionary`2[TKey,TValue].get_Item (System.Collections.Concurrent.TKey key) in /private/tmp/source-mono-mac-4.2.0-branch/bockbuild-mono-4.2.0-pre2-branch/profiles/mono-mac-xamarin/build-root/mono-4.2.0/external/referencesource/mscorlib/system/collections/Concurrent/ConcurrentDictionary.cs:line 955
   at Unosquare.Labs.EmbedIO.Modules.LocalSessionModule.<.ctor>b__4_0 (Unosquare.Labs.EmbedIO.WebServer server, System.Net.HttpListenerContext context) in <filename unknown>:line 0
   at Unosquare.Labs.EmbedIO.WebServer.ProcessRequest (System.Net.HttpListenerContext context) in <filename unknown>:line 0

How do I map url to static folder?

If I start web server with url http://+:8000/ and some static folder, say D:\web, request to http://127.0.0.1:8000/ maps to D:\web\Index.html. If I start web server with url http://+:8000/SomeName/, request to http://127.0.0.1:8000/SomeName/ maps to D:\web\SomeName\Index.html. How can I configure server that url part which is supplied in constructor is not included in static file path? I.e. If I start webserver on http://+:8000/SomeName/ and static folder is D:\web, request to http://+:8000/SomeName/ would map to D:\web\index.html

How to control caching headers?

Is there an easy way to tell the static file server to set all the proper headers to disable browser cache for every request?

For instance:

Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Expires: 0

.Net 2.0

Hello,

is it possible (with reasonable amount of work) to compile embedio against .NET 2.0.
I would like to use it within Unity3D.
Or could you tell me which modules I could remove to compile it against .Net 2.0 (I'm just using the "WebApiModule"-Module).

kind regards

Unable to access twice to request.InputStream

How to reproduce (in the ResApiSample.cs) :

            [WebApiHandler(HttpVerbs.Post, RelativePath + "people/*")]
            public async Task<bool> PostPeople(WebServer server, HttpListenerContext context)
            {
                    ...
                    var post = context.RequestFormData(); // OK
                    var model = context.ParseJson<GridDataRequest>(); // will be null
                    ...
            }

OR

            [WebApiHandler(HttpVerbs.Post, RelativePath + "people/*")]
            public async Task<bool> PostPeople(WebServer server, HttpListenerContext context)
            {
                    ...
                    var model = context.ParseJson<GridDataRequest>(); // OK
                    var post = context.RequestFormData(); // will be null
                    ...
            }

The problem come from the underlying inputStream : when StreamReader is disposed, it lets the cursor position to the end. So the next call to StreamReader(inputStream) will be null.

         using (var body = request.InputStream) {
                using (var reader = new StreamReader(body, request.ContentEncoding)) {
                    var stringData = reader.ReadToEnd();

                    if (string.IsNullOrWhiteSpace(stringData)) return null;
                    return stringData.Split('&')
                        .ToDictionary(c => c.Split('=')[0],
                            c => WebUtility.UrlDecode(c.Split('=')[1]));
                }
            }

I've tried to use Read(pos, len) or force body.Position = 0 but this stream cannot be seek or written. Same problem using a MemoryStream and CopyTo... Do you have an idea to fix it ?

Wildcards only supported at the end of a URL?

Correct me if I'm mistaken, but it seems like the "*" wildcard is only supported at the end of a URL rather than anywhere within it. Is this intentional? Looking through the documentation, I don't see any examples of a wildcard not at the end of a URL. Some of my endpoints require a wildcard in the middle of a URL, and I'm sure other developers have the same requirements.

context.UserEndPoint - NullReferenceException

I get error when try to read context.UserEndPoint in OnClientDisconnected() and sometimes in OnMessageReceived() hooks

in Unosquare.Net.HttpConnection.get_RemoteEndPoint() in C:\Unosquare\embedio\src\Unosquare.Labs.EmbedIO\System.Net\HttpConnection.cs: 140
in Unosquare.Net.WebSocketContext.get_UserEndPoint() in C:\Unosquare\embedio\src\Unosquare.Labs.EmbedIO\System.Net\WebSocketContext.cs: 233

Client is local, connecting from the same computer

embedio version 1.4.6.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.