首页 > 开发 > 综合 > 正文

Creating a Webservice Part 1 of 2

2024-07-21 02:21:35
字体:
来源:转载
供稿:网友
with some help from the great guys from secure webs, i decided to expose my site, http://www.123aspx.com , as a web service. i wanted to start with something simple, so i decided to expose the "what's new" asp.net resources. the "what's new" section contains the latest 12 additions to my site. here is a quick tutorial around writing that webservice.
webservices in asp.net are built around the soap (simple object access protocol) and wsdl (web services description language). we're not going to get into these standards (wsdl, and soap), but instead, focus on creating a webservice and consuming it.


planning
i decided to return a dataset object as my collection of new resources. i chose a dataset because most asp.net developers are already familiar with datasets, and they can easily be bound to datagrids. the dataset consists of 4 columns:
name - the name or title of the resource.
url - the url to the resource
domain - the domain name the resource can be found at.
dateupdated - the date the resource was updated

layout
we start programming a webservice by declaring it to the .net engine and importing the following namespaces:
     <%@ webservice language="vb" class="aspx123websvc" %>
    option strict on
    option explicit on
    imports system
    imports system.data
    imports system.data.sqlclient
    imports system.web
    imports system.web.services
    imports microsoft.visualbasic
we also need to tell the compiler that the class "aspx123websvc" will be webservice enabled. we do this by inheriting the webservice namespace in the class declaration.
public class aspx123websvc : inherits webservice  
now that we have our classes defined, i went ahead and declared the main function.

getting to it
because we are declaring a method here, we need to mark it as a webservice method using <webmethod()>
public function getnewresources() as dataset  
i decided to add a friendly description to this method, to tell the consumer what this method does. when we view the default wsdl, supplied natively by asp.net, our description will show be available to the consuming programer. once we have our functions and classes declared, writing a webservice is just like writing any other codebehind file.

accessing the database
now that i have my webservice framework in place, let's go ahead and get our our data. in this example, i need to massage the data a little bit, specifically the domain name of the asp.net resource. so what i decided to do, was to return a datareader, strip off only the domain name of the resource (instead of returning the complete url), and then build the dataset that we will eventually be returning. to access the database i use 2 utility functions. one function is called getdatareader( ) and the other function is called sqlconnstring(). . getdatareader() returns a sqldatareader, it also takes advantage of system.data.commandbehavior.closeconnection. system.data.commandbehavior.closeconnection is a parameter that tells the framework to close the datareader as soon as i'm done reading from it. sqlconnstring() is used to read my sql server connection string from the web.config file. i've included a snippet from my web.config file to display how i'm adding an appsettings section to web.config.  
getdatareader()
private function getdatareader(sqltext as string) as sqldatareader
    dim dr as sqldatareader
    dim sqlconn as sqlconnection = new sqlconnection( sqlconnstring() )
    dim sqlcmd as sqlcommand = new sqlcommand( sqltext, sqlconn )
     
    sqlcmd.connection.open()
    dr = sqlcmd.executereader( system.data.commandbehavior.closeconnection )

    return dr
end function

sqlconnstring()
private function sqlconnstring() as string
    return system.configuration.configurationsettings.appsettings("websvcdb")
end function

web.config
<appsettings>
<add key="websvcdb" value="password=;user id=sa;initial catalog=pubs;data source=127.0.0.1;" />
</appsettings>  

getting the data
i have a stored procedure called "s_res_whats_new". i execute the stored procedure to return the datareader.  i also create my dataset that i will be passing back to the webservice.
rem -- get the data from the database
dim sqltext as string = "exec s_res_whats_new"
dim dbread as sqldatareader = getdatareader( sqltext )

rem -- create the datatable
dim ds as dataset = new dataset("newresources")
dim dt as datatable = ds.tables.add("resourcelist")
dim dr as datarow




assembling the dataset
once i had a datareader back from my database, full of new resources, i loop through the datareader to create a dataset.  the reason i didn't bring back the dataset directly, is because i needed to modify some of the data, before i sent it out as the webservice, mainly the date and domain name. i modify the date, to have a short date format, and i modify the url to only return the domain name part of the url. for example, if i was referencing the resource http://www.aspfree.com/authors/default.asp, i only want to return www.aspfree.com. once i have the parameters url, dateupdated, domain, and resource name, i add them to a datarow and add the datarow to a datatable, which is part of the dataset. here is the code i use to loop through the datareader and compile the dataset.  
rem -- get the data from the database
dim sqltext as string = "exec s_res_whats_new"
dim dbread as sqldatareader = getdatareader( sqltext )

rem -- create the datatable
dim ds as dataset = new dataset("newresources")
dim dt as datatable = ds.tables.add("resourcelist")
dim dr as datarow

while dbread.read()
    dateupdated = datetime.parse(dbread.item("res_dateupdated").tostring())
    resourcename = dbread.item("res_name").tostring()
    resourceurl = dbread.item("res_url").tostring()
    resourcepk = dbread.item("res_pk").tostring()

    resourcedomain = ""
    if len(resourceurl)>prot_prfx_len then
       rem -- strip off 'http://' and remove everything after .com, .net, or .org, or less than 25 characters
        urlwhatsnew = resourceurl & "/"
        resourcedomain = lcase(left(mid(urlwhatsnew, prot_prfx_len ,instr(prot_prfx_len,urlwhatsnew,"/")-prot_prfx_len),max_domain_len))
    end if
    resourcedate = dateupdated.toshortdatestring()
    resourceurl = "http://www.123aspx.com/resdetail.asp?rid=" & resourcepk

    rem -- add to dataset ds
    dr = dt.newrow()
    dr("url") = resourceurl
    dr("dateupdated") = resourcedate
    dr("domain") = resourcedomain
    dr("name") = resourcename

    dt.rows.add(dr)
end while


here i manipulated the "res_dateupdated" field by first converting it to a date.  because sql server is storing the date as a long date (mm/dd/yy with seconds),  i needed to parse the date to return only mm/dd/yy.  creating a short date can be done by the following line:  
            res_date = date_dateupdated.toshortdatestring()  
i added each local variable to a column in a datarow, and then added the row to the dataset. after the datareader had finished looping, i returned the dataset.

testing
http://aspfree.com/authors/123aspx/createwebsvc/images/test123aspxws.jpg
now it was time to test my webservice.  asp.net provides a default page for testing webservices.  if you look closely, you will see the description:"returns the latest 12 new and updated resources at http://www.123aspx.com" that we used to describe our method getnewresources.here is a screenshot.

asp.net returns a webservice in the form of the industry strandard, wsdl protocol. wsdl is an xml document that will tell the consumer what methods are available to be called, and can be considered a type of api. we can now test our webservice by clicking the invoke button.  here is a screen shot of the first 3 rows of data that will be sent to the consumer.
http://aspfree.com/authors/123aspx/createwebsvc/images/wsresults.jpg
conclusion
asp.net makes it extremely easy for us to build webservices. once we have a basic understanding of how asp.net works, it isn't that hard to extend our knowledge to webservices
菜鸟学堂:
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表