[英]WCF REST with a clean URL
我正在考虑托管基于IIS 7的WCF Rest Service。访问我的服务的URL将类似于
api.mycompany.com/applicationName/Service.svc/users/1347
最近,我一直在寻找一些使用干净URL的REST API实现,例如Yahoo API
social.yahooapis.com/v1/user/{guid}/contacts
考虑到我不想在URL中包含应用程序名称和.svc,因此我想知道最好的WCF主机环境(例如Windows Service)或任何解决方案(例如URL重写模块)是什么,以便我可以拥有一个完全干净的URL对于我的REST API
您可以在.NET 4中使用新的WebApi模板,该模板为您提供在global.asax中指定路由的功能。 这完全摆脱了svc文件。 您需要具有AspNetCompatilbityMode = true。 请参见下面的示例:
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class RestService
{
// TODO: Implement the collection resource that will contain the SampleItem instances
private static List<SampleItem> sampleCollection = new List<SampleItem>();
[WebGet]
public List<SampleItem> GetCollection()
{
// TODO: Replace the current implementation to return a collection of SampleItem instances
if (sampleCollection.Count == 0)
{
sampleCollection = new List<SampleItem>();
sampleCollection.Add(new SampleItem() { Id = 1, StringValue = "Hello 1" });
sampleCollection.Add(new SampleItem() { Id = 2, StringValue = "Hello 2" });
sampleCollection.Add(new SampleItem() { Id = 3, StringValue = "Hello 3" });
sampleCollection.Add(new SampleItem() { Id = 4, StringValue = "Hello 4" });
sampleCollection.Add(new SampleItem() { Id = 5, StringValue = "Hello 5" });
}
return sampleCollection;
}
}
您的web.config将具有以下内容:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</modules>
</system.webServer>
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<standardEndpoints>
<webHttpEndpoint>
<!--
Configure the WCF REST service base address via the global.asax.cs file and the default endpoint
via the attributes on the <standardEndpoint> element below
-->
<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/>
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
最后,您的Global.asax如下所示:
public class Global : HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes();
}
private void RegisterRoutes()
{
// Edit the base address of Service1 by replacing the "Service1" string below
RouteTable.Routes.Add(new ServiceRoute("RestService", new WebServiceHostFactory(), typeof(RestService)));
}
}
现在,您的服务的网址为:
http://localhost/SampleApp/RestService/GetCollection
现在您有了干净正确的REST URL
您可以使用IIS 7中的URL重写模块来实现此目的。
您可以使用UriTemplate类也可以查看WCF Rest Starter Kit。
这是一个很好的解释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.