简体   繁体   中英

.NET Nancy response with a video file (self hosting)

I am writing a self-hosting server on .NET based on REST architecture with Nancy(version 1.4.4). I preferred to do self-hosting(Nancy.Hosting.Self is version 1.4.1) and one of requires functionalities is to respond for a request with a video file. To make picture clear, my partner writes React application and he needs this video.

I've tried different options:

First I tried Response.AsFile() but when I try to access it by a link, I get 404 with label "The resource you have requested cannot be found." and I have no idea why...

public class HelloModule : NancyModule
{
    public HelloModule()
    {
        Get["/"] = parameters =>
        {
            return Response.AsFile(@"C:\7\video112018.mp4","video/mp4");
        };
    }
}

Second variant was to use GenericFileResponce like in the code below, but it leads to the same problem:

public class HelloModule : NancyModule
{
    public HelloModule()
    {
        Get["/"] = parameters =>
        {
            GenericFileResponse fileResponse = new GenericFileResponse(@"C:\7\video112018.mp4");
            return fileResponse;
        };
    }
}

Last option I tried was to write directly to response stream like in the code below, but in this case an error "The specified network name is no longer available" occurs. And what makes it tricky is that this error occurs sometimes but I didn't find any dependency where it comes from...

public class HelloModule : NancyModule
{
    public HelloModule()
    {
        Get["/"] = parameters =>
        {
            return new Response
            {
                ContentType = "video/mp4",

                Contents = s =>
                {
                    String fileName = @"C:\7\video112018.mp4";
                    using (var stream = new FileStream(fileName, FileMode.Open))
                        stream.CopyTo(s);
                    s.Flush();
                    s.Close();
                }
            };
        };
    }
}

I would really appreciate if you have any suggestions about these solutions or give another one.

PS I also tried to send an image, it works with third approach but not with first or second

PPS don't judge the code strictly, because it's only an example)

I was able to do very basic streaming of video files by doing this:

Get["/"] = p =>
{
    var file = new FileStream(@"PATH_TO_FILE", FileMode.Open);
    return new StreamResponse(() => file, "video/mp4");
}

This allowed video files to play, but there was no seeking.

In the end I found this post. Adding these extensions allows for the video to be seeked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM