从Excel中使用安全的ASP.Net WebAPI

时间:2013-12-16 03:18:27

标签: excel-vba asp.net-web-api vba excel

是否可以使用需要从Excel进行身份验证的WebAPI? 对于常规.Net客户端,我们将身份验证凭据发送到WebAPI的令牌端点并获取令牌,然后在后续调用中将其作为承载附加。 但这是如何通过Excel完成的?需要在后面的VBA代码中使用哪些对象?

WebAPI正在返回一组对象,这些对象需要在Excel中显示为列和行。

1 个答案:

答案 0 :(得分:1)

你还记得XHR,还是我应该说XML HTTP Request :)?

这是我在我的项目上编写的一个示例,用于验证调用从Oracle数据库返回数据的Web服务的用户:

Dim xhr As Object

On Error Resume Next
Set xhr = CreateObject("MSXML2.XMLHTTP")

If Err.Number <> 0 Then
    Set xhr = CreateObject("MSXML.XMLHTTPRequest")
    Application.StatusBar = "Error 0, has occured while creating a MSXML.XMLHTTPRequest object"
End If

If xhr Is Nothing Then
    Application.StatusBar = "For some reason it wasn't possible to make a MSXML2.XMLHTTP object"
    Exit Function
End If

'consuming the web service.
xhr.Open "POST", "/webservice/url/goes/here", False
xhr.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
xhr.send "post parameters can be sent here format: paramname=paramvalue&paramname2=paramvalue2"

If xhr.Status = 200 Then    
    'creating the XmlDocument to load the received data.
    Dim xDoc As MSXML2.DOMDocument60
    Set xDoc = CreateObject("Msxml2.DOMDocument.6.0")
    xDoc.setProperty "ProhibitDTD", False
    xDoc.setProperty "ResolveExternals", True

    'loading the data into the in-memory xml document.
    xDoc.validateOnParse = True
    xDoc.async = False
    xDoc.LoadXML xhr.responseText
    Application.StatusBar = False

    'xDoc now holds your web service returned data
End If

上述代码可用于连接到Web服务。 在此链接http://www.mcpher.com/Home/excelquirks/snippets/basicauth中,有关如何实现基本身份验证的详细信息。

希望这可以帮助你一路走来,

问候。