如何删除RESTful WCF服务中的“.svc”扩展?

据我所知,RESTful WCF在其URL中仍然有“.svc”。

例如,如果服务接口是这样的

[OperationContract] [WebGet(UriTemplate = "/Value/{value}")] string GetDataStr(string value); 

访问URI就像“ http://machinename/Service.svc/Value/2 ”。 在我的理解中,REST的一部分优势是可以隐藏实现细节。 像“ http:// machinename / Service / value / 2 ”这样的RESTful URI可以由任何RESTful框架实现,但是“ http://machinename/Service.svc/value/2 ”暴露了它的实现是WCF。

如何删除访问URI中的“.svc”主机?

在IIS 7中,您可以使用本博客文章中所述的Url重写模块 。

在IIS 6中,您可以编写一个将重写url的http模块 :

 public class RestModule : IHttpModule { public void Dispose() { } public void Init(HttpApplication app) { app.BeginRequest += delegate { HttpContext ctx = HttpContext.Current; string path = ctx.Request.AppRelativeCurrentExecutionFilePath; int i = path.IndexOf('/', 2); if (i > 0) { string svc = path.Substring(0, i) + ".svc"; string rest = path.Substring(i, path.Length - i); ctx.RewritePath(svc, rest, ctx.Request.QueryString.ToString(), false); } }; } } 

还有一个很好的例子,如何在不使用第三方ISAPI模块或通配符映射的情况下在IIS 6中实现无延伸的URL。

我知道这个post现在已经有点老了,但是如果你碰巧使用了.NET 4,你应该看看使用URL路由(在MVC中引入,但带入了核心ASP.NET)。

在您的应用程序启动(global.asax)中,只需要使用以下路由configuration行来设置默认路由:

 RouteTable.Routes.Add(new ServiceRoute("mysvc", new WebServiceHostFactory(), typeof(MyServiceClass))); 

那么你的url将如下所示:

 http://servername/mysvc/value/2 

HTH

以下是使用IIS 7重写模块或使用自定义模块的更详细的信息: http : //www.west-wind.com/Weblog/posts/570695.aspx

还有一种方法可以完全消除物理.svc文件。 这可以通过VirtualPathProvider完成。

请参阅: http : //social.msdn.microsoft.com/Forums/en-US/wcf/thread/350f2cb6-febd-4978-ae65-f79735d412db

它很容易在IIS 7上 – 使用URL重写模块

在IIS 6上,我发现它最容易使用ISAPI重写模块 ,它允许您定义一组正则expression式,将请求Url映射到.svc文件中。

在IIS6或7中,您可以使用IIRF ,一个免费的重写filter。 这是我使用的规则:

 # Iirf.ini # RewriteEngine ON RewriteLog c:\inetpub\iirfLogs\iirf-v2.0.services RewriteLogLevel 3 StatusInquiry ON RemoteOk CondSubstringBackrefFlag * MaxMatchCount 10 # remove the .svc tag from external URLs RewriteRule ^/services/([^/]+)(?<!\.svc)/(.*)$ /services/$1.svc/$2 [L] 

将此添加到您的global.asax

 private void Application_BeginRequest(object sender, EventArgs e) { Context.RewritePath(System.Text.RegularExpressions.Regex.Replace( Request.Path, "/rest/(.*)/", "/$1.svc/")); } 

这将通过/Service1.svc/arg1/arg2replace/ rest / Service1 / arg1 / arg2