RESTful WCF Services with No svc file and No config and How to use Service Route
2012-11-14 14:30
651 查看
WhileMicrosoftcontinuestoaddfeaturestoWCFwitheachversion,theyarealsoaddingfeaturesthatsimplifyworkingwithWCFservicesaswell.HistoricallyWCFhasbeensomewhatintimidatingtotheuninitiatedbecauseofthenon-trivialconfigurationforendpointsincludingbehaviors,bindings,andmuchmore.Forthisreason,alotofpeoplestayedwith“oldschool”asmxwebservices.WiththenewfeaturesofWCF4,youcanbuildpowerfulwebserviceswith*no*svcfileand*no*endpointconfiguration.
BuildingaRESTfulWCFserviceinthiswayisquiteeasyandyoudon’tneedrelyonanyitemtemplates.Juststartwithablankasp.netwebapplicationprojectinVisualStudio.Theweb.configfileisvirtuallyempty:
<configuration>
[code]<system.web>
<compilationdebug="true"targetFramework="4.0"/>
</system.web>
</configuration>
[/code]
NextjustaddaregularC#class-forthisexample,IcallminePersonServiceanditwillhavebasicCRUDoperations.TypicallywecreateinterfacesinWCFtodefineourServiceContractandoperationslikethis:
[ServiceContract]
[code]interfaceIPersonService
{
[OperationContract]
PersonGetPerson(stringid);
[OperationContract]
PersonInsertPerson(Personperson);
[OperationContract]
PersonUpdatePerson(stringid,Personperson);
[OperationContract]
voidDeletePerson(stringid);
}
[/code]
Keepinmind,thisstepis*not*required.You*could*decorateyourserviceclassdirectlywiththeseattributesandnotevenhavetheinterfaceatall.However,inthiscase,it’saniceconveniencetoencapsulatealltheWCFattributesontheinterfaceratherthanyourimplementationclass.TheimplementationofourPersonServiceclasslookslikethis(I’veremovedthecodethataccessthedatastoreforbrevity):
[AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)]
[code]publicclassPersonService:IPersonService
{
[WebGet(UriTemplate="Person({id})")]
publicPersonGetPerson(stringid)
{
}
[WebInvoke(UriTemplate="Person",Method="POST")]
publicPersonInsertPerson(Personperson)
{
}
[WebInvoke(UriTemplate="Person({id})",Method="PUT")]
publicPersonUpdatePerson(stringid,Personperson)
{
}
[WebInvoke(UriTemplate="Person({id})",Method="DELETE")]
publicvoidDeletePerson(stringid)
{
}
}
[/code]
ThisisjustanormalC#classthatimplementaninterface.It’salsodecoratedwiththetypicalWebGet/WebInvokeattributes(intheSystem.ServiceModel.Webnamespace)thatweuseforRESTfulservices.Alsonoticethat3ofthe4methodshavethesameUriTemplatebuttheyaredifferentiatedbytheHTTPmethod(i.e.,GET/PUT/DELETE).AlsonoticetheAspNetCompatibilityRequirementsattribute–thisisneededforRESTfulservicesthatareprocessedintheASP.NETpipelineas
<system.serviceModel>
[code]<serviceHostingEnvironmentaspNetCompatibilityEnabled="true"/>
</system.serviceModel>
[/code]
SohowdowetakethisregularC#classandmakeitintoaservicewithoutan*.svcfile?TheSystem.Web.RoutinginfrastructurehasnowbeenincorporatedintoWCF4tomakethispossible.Justaddthelineofcode(line#5)toyourglobal.asax:
publicclassGlobal:System.Web.HttpApplication
[code]{
protectedvoidApplication_Start(objectsender,EventArgse)
{
RouteTable.Routes.Add(newServiceRoute("",newWebServiceHostFactory(),typeof(PersonService)));
}
}
[/code]
The
That’sit!YounowhaveafullyfunctioningRESTfulWCFservicethatyoucanfullytestwith
OneinterestingaspecttoallthisisthatyoucandoallthisinMVCaswell.Infact,ItypicallydouseMVCtoreturnJSONtoviewsforAJAXcallsinmyMVCapps.However,ifyouwerebuildingstand-aloneservicesforthis,wouldMVCbeeasierthantheexampleofabove?Keepinmind,wecouldsimplifytheexampleaboveevenfurtherbyeliminatingtheIPersonServiceinterfacealltogether.IdaresaythatsettingupRESTfulroutesliketheonesshownaboveiseasierwithWCFthanMVC(this,comingfroman“MVCguy”)becausewecanapplytheUriTemplatesdirectlytothemethods.ToaccomplishthesameinMVC,youhavetocreatecustomrouteconstraintstoavoidthenameoftheC#methodsfromshowingupintheURL(andhonoringtheRESTHTTPverbs).Ifyouaregoingtodothis,Ireallyliketheapproach
Infact,usingtheWCFinfrastructuregetsyouevenmorefeaturesforfree.Forexample,ifweadd1morelineofconfiguration(checkoutline#5below)wegetahelppageandautomaticformatselectionforfree!Nowourentireconfigurationjustlookslikethis(andstillnoWCFendpointconfigurationneeded):
<system.serviceModel>
[code]<serviceHostingEnvironmentaspNetCompatibilityEnabled="true"/>
<standardEndpoints>
<webHttpEndpoint>
<standardEndpointname=""helpEnabled="true"automaticFormatSelectionEnabled="true"/>
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
[/code]
Noticeallwehadtodotogetthehelppagewastherequest“/help”:
TheautomaticformatselectioninWCFwillhonortheAcceptheaderand/ortheContent-typeheaderandreturnXML,JSON,etc.tothecallerbasedonthevaluespecifiedintheheader.Again,thattakescustomcodeinMVCwhichyougetforfreeinWCF.
相关文章推荐
- Service Station - An Introduction To RESTful Services With WCF
- How to use jquery ajax and android request security RESTful WCF
- How and Why to use the System.servicemodel.MessageParameterAttribute in WCF
- Android upload large file to WCF restful service
- how to use Properties and File to Save Data
- How to mount partition with ntfs file system and read write access
- Visual C++ Debugging: How to use 'ASSERT' and deal with assertions failures?
- How to use .netrc file on windows to save user and password
- EF How to use context.Set and context.Entry, which ships with EF4.1 ?
- How to Call WCF Services Synchronously and Asynchronously
- How to create, host, test and consume a WCF Web Service
- How to use InterfaceInterceptor of Unity with configuration file
- RestFul WCF JSON Service with client and on Mozilla Firefox –REST Client
- how to config and use apt-get
- How to use UTF-8_with_BOM, XML and Java together
- How to Use Oradebug to Get Trace File Name and Location
- How to create fully custom Role, User, Event, Resource classes for use with the Security and Scheduler modules
- How to combine WCF Route and MVC Route to work together.
- How to change service accounts and service account passwords in SharePoint Server 2007 and in Windows SharePoint Services 3.0
- how to use adb and gdbserver with VirtualBox - KVM (qemu)