如何删除RESTful WCF服务中的".svc"扩展名?

Mor*_*eng 51 rest wcf

据我所知,RESTful WCF的URL中仍然有".svc".

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

[OperationContract]
[WebGet(UriTemplate = "/Value/{value}")]
string GetDataStr(string value);
Run Code Online (Sandbox Code Playgroud)

访问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"主机?

Thi*_*lva 47

我知道这篇文章现在有点旧了,但是如果你碰巧使用.NET 4,你应该看一下使用URL Routing(在MVC中引入,但是带入了核心ASP.NET).

在您的app start(global.asax)中,只需使用以下路由配置行来设置默认路由:

RouteTable.Routes.Add(new ServiceRoute("mysvc", new WebServiceHostFactory(), typeof(MyServiceClass)));
Run Code Online (Sandbox Code Playgroud)

那么您的网址将如下所示:

http://servername/mysvc/value/2
Run Code Online (Sandbox Code Playgroud)

HTH

  • 如果项目不存在,请不要忘记将"System.ServiceModel.Activation"的引用添加到项目中.(VS2012中的默认WCF项目似乎不包括此内容) (5认同)
  • 更清洁的解决方案.谢谢! (2认同)
  • 最佳解决方案(如果使用 4.0) (2认同)

Dar*_*rov 30

在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);
            }
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

并且有一个很好的例子,如何在IIS 6中实现无扩展URL而不使用第三方ISAPI模块或通配符映射.