您的位置:首页 > 编程语言 > ASP

Nancy和ASP.NET MVC的简单对比

2015-06-19 02:40 696 查看
Nancy的优势在哪里?和微软的MVC比有什么不同,哪个更好?Nancy是否可以脱离IIS等等,那么今天就拿MVC和Nancy做个简单的对比吧。

今天主要讲理论的东西,不写代码,文章中所提到的配置,只是为了帮助理解,详细配置和操作内容还请参考官方帮助文档。

一、Hosting Of Nancy

1、Hosting Nancy with asp.net

方案一:整站都使用Nancy

  在ASP.NET中,Nancy通过设置web.config,使用HTTP handler来处理请求。如果你在Visual Studio中使用了Nancy的模板来创建,就会自动生成webconfig配置,否则就要添加如下配置到webconfig中:

<system.web>

<compilation debug="true" targetFramework="4.0" />

<httpHandlers>

<add verb="*" type="Nancy.Hosting.Aspnet.NancyHttpRequestHandler" path="*"/>

</httpHandlers>

</system.web>

<system.webServer>

<modules runAllManagedModulesForAllRequests="true"/>

<validation validateIntegratedModeConfiguration="false"/>

<handlers>

<add name="Nancy" verb="*" type="Nancy.Hosting.Aspnet.NancyHttpRequestHandler" path="*"/>

</handlers>

</system.webServer>

并且还要确定你添加了Nancy和Nancy.Hosting.Aspnet 两个dll的引用。

方案二:网站中一部分使用Nancy

除了使用Nancy搭建整个网站,我们还可以在已存在的网站中使用Nancy来处理某些特定路径的请求。例如我们要处理nancypath下面的所有请求,我们只需要修改上面的配置NancyHttpRequestHandler的path为path="nancypath/*",并且你也要在项目中添加指定路径的文件夹,并在文件夹内放入如下Web.config:

<?xml version="1.0"?>

<configuration>

<system.web>

<httpHandlers>

<add verb="*" type="Nancy.Hosting.Aspnet.NancyHttpRequestHandler" path="*"/>

</httpHandlers>

</system.web>

</configuration>

除此之外,再修改webconfig中的<location>节点配置。

方案三:在MVC中使用Nancy

是的,你没有看错,Nancy和MVC一起使用,如果要在MVC中使用Nancy,需要修改Global.asax.cs文件,添加如下内容:

routes.IgnoreRoute("nancy/{*pathInfo}");

这个时候,所有访问nancy目录的请求,就都会被Nancy处理了,接下来,我们就可以这样写代码了,例如:

public class Home : NancyModule

{

public Home()

{

Get["/nancy/products"] = x => "The products!";

}

}

这部分详细内容参考:https://github.com/NancyFx/Nancy/wiki/Hosting-Nancy-with-asp.net

2.Hosting Nancy with wcf

  如果你想搭建一个轻量级的HTTP服务而又不想使用IIS,Nancy是一个很好的选择,你可以按照下面的操作来实现:

首先,安装
Nancy.Hosting.Wcf,Nugget代码如下:


PM> Install-Package Nancy.Hosting.Wcf

然后,编写代码,如下:

var host = new WebServiceHost(new NancyWcfGenericService(),                              new Uri("http://localhost:1234/base/"));
host.AddServiceEndpoint(typeof (NancyWcfGenericService), new WebHttpBinding(), "");
host.Open();// Nancy will now handle requests to http://localhost:1234/base/

然后,Nancy就会侦听本地的1234端口,处理HTTP请求。

这部分详细内容参考:https://github.com/NancyFx/Nancy/wiki/Hosting-Nancy-with-wcf

除此之外,Nancy还有以下Host方式:

Hosting-nancy-with-azure       参考:https://github.com/NancyFx/Nancy/wiki/Hosting-nancy-with-azure

Hosting-nancy-with-owin       参考:https://github.com/NancyFx/Nancy/wiki/Hosting-nancy-with-owin

Hosting-Nancy-with-Umbraco       参考:https://github.com/NancyFx/Nancy/wiki/Hosting-Nancy-with-Umbraco

Hosting-Nancy-with-Nginx-on-Ubuntu 参考:https://github.com/NancyFx/Nancy/wiki/Hosting-Nancy-with-Nginx-on-Ubuntu

Hosting-Nancy-with-FastCgi        参考:https://github.com/NancyFx/Nancy/wiki/Hosting-Nancy-with-FastCgi

Self-Hosting-Nancy             参考:https://github.com/NancyFx/Nancy/wiki/Self-Hosting-Nancy

二、MVC和Nancy中的路由对比

1、Nancy中的路由机制

在上一篇的博文中,我们都知道Nancy中的所有路由都定义在module中的构造方法中,我们上次定义了一个无参路由,如下:

public class HelloModule : NancyModule

{

public HelloModule()

{

Get["/"] = parameters => "Hello World";

}

}

Nancy中有参路由可以这样定义:

public class ProductsModule : NancyModule

{

public ProductsModule()

{

Get["/products/{id}"] = _ =>

{

//do something

};

}
}

或者定义成异步的,如下:

public class ProductsModule : NancyModule

{

public ProductsModule()

{

Get["/products/{id}", runAsync: true] = async (_, token) =>

{

//do something long and tedious

};

}
}

Nancy中支持的method有:
DELETE
,
GET
,
HEAD
,
OPTIONS
,
POST
,
PUT
and
PATCH
.


当然,Nancy中还支持路由参数约束,例如我们要求参数必须为int类型,我们可以这样定义:

Get["/intConstraint/{value:int}"] = _ => "Value " + _.value + " is an integer.";

除了int类型,Nancy还支持以下类型的约束:

感觉还不够?Nancy还提供了自定义参数约束,比如我们要求参数是一个email,我们可以先定义如下类:

public class EmailRouteSegmentConstraint : RouteSegmentConstraintBase<string>

{

public override string Name

{

get { return "email"; }

}

protected override bool TryMatch(string constraint, string segment, out string matchedValue)

{

if (segment.Contains("@"))

{

matchedValue = segment;

return true;

}

matchedValue = null;

return false;

}
}

然后,定义路由如下:

Get["/profile/{value:email}"] = _ => "Value " + _.value + " is an e-mail address.";

下面是Nancy中路由常用的几种写法:



当然,Nancy的路由机制非常强大、非常灵活,那么当一个地址可以匹配多个路由时,Nancy会选择哪一个呢?其实,Nancy中有一套路由的权重机制来解决路由冲突,这个到后面说路由的时候会详细说的。

2、MVC中的路由机制

我们都知道MVC中的路由配置都在 Global.asax.cs中,当一个ASP.NET MVC应用程序第一次运行时, Application_Start()方法被调用。这个方法,又调用RegisterRoutes()方法,RegisterRoutes()方法创建了路由表。

MVC中的默认路由如下:

public static void RegisterRoutes(RouteCollection routes)

{

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(

"Default", // 路由名称

"{controller}/{action}/{id}", // 带有参数的 URL

new { controller = "Home", action = "Index", id = UrlParameter.Optional } // 参数默认值 (UrlParameter.Optional-可选的意思)

);
}

NVC中无参路由定义如下:

routes.MapRoute
(    "Home",
"{controller}/{action}/{id}");

MVC中带命名空间的路由定义如下:

routes.MapRoute(      "AdminControllers", // 路由名称
"{controller}/{id}-{action}", // 带有参数的 URL
new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // 参数默认值
new string[] { "Admin.Controllers" }//命名空间
);

MVC中带约束的路由定义如下:

routes.MapRoute(    "RuleControllers",    "{controller}/{action}-{Year}-{Month}-{Day}}",    new { controller = "Home", action = "Index", Year = "2014", Month = "12", Day = "08" },    new { Year = @"^\d{4}", Month = @"\d{2}" } //4位数 2位数);

MVC全局路由:

routes.MapRoute(        "All", // 路由名称
"{*Vauler}", // 带有参数的 URL
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // 参数默认值
);


综上所述,MVC和Nancy的路由机制从功能上来说不相上下,MVC有的Nancy也有。不过,相比之下,Nancy中的路由更加简单、灵活,毕竟MVC中的路由对于新手来说不是那么容易掌握的。

三、MVC和Nancy中的视图的对比

  当然,视图这块大家还是比较关注的。下面简单对比MVC和Nancy所支持的视图:

 MVCNancy
WebForm支持支持
Razor支持支持
这里我们看到MVC和nancy都支持WebForm和Razor视图。并且,Nancy在Razor视图中也支持Model的绑定和部分视图,在Nancy中的部分视图中,也可以使用Modle绑定。

原文链接:http://www.cnblogs.com/yunfeifei/p/4149953.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  开发工具 .net