Nancy - 使用 owin 承载

What is OWIN?

OWIN defines a standard interface between .NET web servers and web applications. The goal of the OWIN interface is to decouple server and application, encourage the development of simple modules for .NET web development, and, by being an open standard, stimulate the open source ecosystem of .NET web development tools. For more information please visit the official website at http://owin.org/

Katana

Katana is OWIN implementations for Microsoft servers and frameworks.

Katana - ASP.NET Host

Note: Assumes your project is an ASP.NET project with Nancy.dll referenced and without any Nancy.Hosting.xxxxx.dll referenced.

  • Install package using Nuget
Install-Package Microsoft.Owin.Host.SystemWeb
Install-Package Nancy.Owin
  • Add the following key in web.config. (This is required for the current v1.0.1 for SystemWeb OWIN host and is likely to be removed in future versions.)
<appSettings>
    <add key="owin:HandleAllRequests" value="true"/>
</appSettings>
  • Create an OWIN startup file
using Owin;
using Nancy.Owin;

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.UseNancy();
    }
}

Note: You must keep the Startup file‘s namespace the same as your application name or it will return a 403.14 - Forbidden.

  • Edit web.config Only if you are using PUT, HEAD or DELETE verbs
<system.webServer>
<handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>

NOTE! You might have to perform an extra step to get custom static content conventions and diagnostics to work:

Katana - HttpListener (SelfHost)

  • Install packages using NuGet
Install-Package Microsoft.Owin.Hosting
Install-Package Microsoft.Owin.Host.HttpListener
Install-Package Nancy.Owin
  • Create an OWIN startup file
using Owin;

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.UseNancy();
    }
}
  • Main Entry Point
using Microsoft.Owin.Hosting;

class Program
{
    static void Main(string[] args)
    {
        var url = "http://+:8080";

        using (WebApp.Start<Startup>(url))
        {
            Console.WriteLine("Running on {0}", url);
            Console.WriteLine("Press enter to exit");
            Console.ReadLine();
        }
    }
}
  • Run Visual Studio or the compiled executable in admin mode.

Running without Admin mode

Note that on Windows hosts a HttpListenerException may be thrown with an Access Deniedmessage. To resolve this the URL has to be added to the ACL.

On Windows Vista/Server 2008 or later, execute the following in PowerShell or CMD running as administrator:

netsh http add urlacl url=http://+:8080/ user=DOMAIN\username

Replace DOMAIN\username with your domain and username or your computer name and username if you are not joined to a domain. See http://msdn.microsoft.com/en-us/library/ms733768.aspx for more information. You can find the user with whoami command.

You can remove the urlacl using the following command.

netsh http delete urlacl url=http://+:8080/

Also but the port may need to be opened on the machine or corporate firewall to allow access to the service.

Accessing OWIN environment variables

public class HomeModule : NancyModule
{
    public HomeModule()
    {
      Get["/"] = x => {
            var env                 = this.Context.GetOwinEnvironment();

            var requestBody         = (Stream)env["owin.RequestBody"];
            var requestHeaders      = (IDictionary<string, string[]>)env["owin.RequestHeaders"];
            var requestMethod       = (string)env["owin.RequestMethod"];
            var requestPath         = (string)env["owin.RequestPath"];
            var requestPathBase     = (string)env["owin.RequestPathBase"];
            var requestProtocol     = (string)env["owin.RequestProtocol"];
            var requestQueryString  = (string)env["owin.RequestQueryString"];
            var requestScheme       = (string)env["owin.RequestScheme"];

            var responseBody        = (Stream)env["owin.ResponseBody"];
            var responseHeaders     = (IDictionary<string, string[]>)env["owin.ResponseHeaders"];

            var owinVersion         = (string)env["owin.Version"];
            var cancellationToken   = (CancellationToken)env["owin.CallCancelled"];

            var uri = (string)env["owin.RequestScheme"] + "://" + requestHeaders["Host"].First() +
              (string)env["owin.RequestPathBase"] + (string)env["owin.RequestPath"];

            if (env["owin.RequestQueryString"] != "")
              uri += "?" + (string)env["owin.RequestQueryString"];

            return string.Format("{0} {1}", requestMethod, uri);
      };
    }
}

Conditional pass-through

Nancy in an OWIN pipeline is, by default, terminating. That is, when it fails to resolve a handler or static content, it will complete the request and return a 404. Subsequent middleware will not be invoked. For example, given this Startup...

using Owin;

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app
          .UseNancy()
          .UseOtherMiddleware();
    }
}

...the Middleware UseOtherMiddleware will never be invoked.

In order to configure Nancy to pass-through, you can supply a delegate that is invoked on a per-request basis, after it has been initially handled by Nancy:

using Owin;
using Nancy;

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app
          .UseNancy(options =>
              options.PerformPassThrough = context =>
                  context.Response.StatusCode == HttpStatusCode.NotFound)
          .UseOtherMiddleware();
    }
}

Here, when Nancy is responding with a 404, the request is passed-through to UseOtherMiddlewareand Nancy‘s response (any headers and body) is discarded.

There is also an extension helper make it more succinct if you are just dealing with StatusCodes for pass-through:

using Owin;
using Nancy;

// Needed to use extension helper.
using Nancy.Owin;

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app
          .UseNancy(options => options.PassThroughWhenStatusCodesAre(
              HttpStatusCode.NotFound,
              HttpStatusCode.InternalServerError))
          .UseOtherMiddleware();
    }
}

Extra steps required when usingMicrosoft.Owin.Host.SystemWeb

When you are hosting Nancy using Microsoft.Owin.Host.SystemWeb you need some additional configuration to get it working in IIS.

First of all, in your OWIN Startup.cs you will need to addapp.UseStageMarker(PipelineStage.MapHandler), for example:

using Microsoft.Owin.Extensions;
using Owin;

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.UseNancy();
        app.UseStageMarker(PipelineStage.MapHandler);
    }
}

You will also have to add the following to your Web.config:

<system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
</system.webServer>

Without this additional configuration, the StaticFileModule from OWIN would intercept the request and return a 404.

时间: 2024-11-04 22:12:55

Nancy - 使用 owin 承载的相关文章

用Web api /Nancy 通过Owin Self Host简易实现一个 Http 服务器

过去做 端游的Http 服务器 用的WebApi 或者Mvc架构,都是放在iis...而我已经是懒出一个地步,并不想去配iis,或者去管理iis,所以我很喜欢 Self host 的启动方式. C#做 http 有2个轻量级的框架, 一个是Nancy ,一个是 微软官方的Web Api 都可以通过owin self host 在应用程序中启动监听 Web Api 官方教程 :https://www.asp.net/web-api/overview/hosting-aspnet-web-api/u

当使用 SelfHost 的 OWIN 承载 SignalR 时,重启 OWIN 后,SignalR 不能正常工作

需要在初始化时,重新对 Resolver 赋值一个新的实例: public class Startup { public void Configuration(IAppBuilder app) { var hubConfiguration = new HubConfiguration {Resolver = new DefaultDependencyResolver()}; app.MapSignalR(hubConfiguration); } } 参考:https://stackoverflo

Nancy之基于Nancy.Owin的小Demo

前面做了基于Nancy.Hosting.Aspnet和Nancy.Hosting.Self的小Demo 今天我们来做个基于Nancy.Owin的小Demo 开始之前我们来说说什么是Owin和Katana 什么是Owin呢? 官网地址:http://owin.org OWIN在.NET Web Servers与Web Application之间定义了一套标准接口,OWIN的目标是用于解耦Web Server和Web Application. 什么是Katana呢? 官网地址:http://kata

Nancy之基于Self Hosting的补充小Demo

前面把Hosting Nancy with ASP.NET.Self Hosting Nancy和Hosting Nancy with OWIN 以demo的形式简单描述了一下. 这篇是为Self Hosting Nancy.和Owin 下面的Self Hosting作个补充. 首先是Self Hosting Nancy的补充: 这里主要是介绍一下Topshelf 官网:http://topshelf-project.com/ GitHub地址:https://github.com/Topshe

给WebAPI的REST接口添加测试页面(二)

在上篇文章中,我对Swagger-UI的基本功能进行了一些介绍,今天在这里介绍一下如何在WebAPI中集成Swagger-UI.这里以一个简单的CRUD的REST服务为例. 1 /// <summary> 2 /// 用户管理 3 /// </summary> 4 public class UserController : ApiController 5 { 6 static List<User> _users = new List<Controllers.Use

ASP.NET Identity详解

Asp.Net Identiy是ASP.NET身份验证机制. 如何构建安全的Web应用? 我们先来思考一个问题:如何构建安全的WEB应用? 一直以来,这都是比较热门的话题.不幸的是,目前还没有一种万能方法,来保证您的WEB应用是绝对安全的.不管是系统本身的漏洞,还是其他外来的攻击,我们每天都饱受着安全问题的煎熬. 其实,我们也无需沮丧和纠结.既然,我们不能阻止攻击,但是可以提前预防,尽量将损失减到最小,不是吗? 目前,有许多适用于ASP.NET应用的安全原则,比如深度防御.不信任任何输入数据.关

Topshelf 和 Katana:统一的 Web 和服务体系结构

转自:https://msdn.microsoft.com/zh-cn/magazine/dn745865.aspx ASP.NET Topshelf 和 Katana:统一的 Web 和服务体系结构 Wes McClure 下载代码示例 使用 IIS 托管 ASP.NET Web 应用程序已成为业界标准十年有余.构建此类应用程序的过程相对简单,但部署它们则并不容易.部署此类应用程序需要掌握应用程序配置层次结构的精妙知识.IIS 历史版本的细微差别,以及对网站.应用程序和虚拟目录的繁琐设置.许多

初识Identity

摘要 通过本文你将了解ASP.NET身份验证机制,表单认证的基本流程,ASP.NET Membership的一些弊端以及ASP.NET Identity的主要优势. 文件夹 身份验证(Authentication)和授权(Authorization) ASP.NET身份验证方式 理解表单验证流程 认识ASP.NET Membership 拥抱ASP.NET Identity ASP.NET Identity主要组成部分 总结 身份验证(Authentication)和授权(Authorizati

asp net core 跨平台初体验

标: 在 ubuntu 16.04 上部署一个 asp.net core 站点,打开网站后显示一段文字. 安装 net core 运行环境:ubuntu 16.04 LTS 1.添加 apt 源 依次执行三条命令 sudo sh -c 'echo "deb [arch=amd64] https://apt-mo.trafficmanager.net/repos/dotnet-release/ xenial main" > /etc/apt/sources.list.d/dotne