简体   繁体   中英

How to pass a parameter using vba to an asp.net web api?

I'm trying to use vba to post to a web api. The problem is that the parameter is blank in the web api. The web api is written in asp. I called the api from c# and it works but I can't get it to work from vba.

Here is the vba call to the api:

Sub Test()

    Dim http As New MSXML2.XMLHTTP60
   
    http.Open "POST", "http://10.5.72.172:108/api/vbaemail", True

    http.SetRequestHeader "Content-type", "application/json"
    
    Call http.send("abc")
   
End Sub

Here's my simple web api.

public void Post([FromBody] string strJson)
{
    SqlConnection cnnCom = null;
    SqlCommand cmdCom = null;
    string strSql = null;

    //write parameter to table
    cnnCom = new SqlConnection(CF.Get_Connection_String(CF.DatabaseName.COMMON));
    cnnCom.Open();
    strSql =
        "INSERT INTO Test( " +
        "F1) " +
        "VALUES( " +
        "'" + strJson + "')";
    cmdCom = new SqlCommand(strSql, cnnCom);
    cmdCom.ExecuteNonQuery();
    cnnCom.Dispose();
}

Here is the working c# call to the web api:

 static void Main(string[] args)
{
    HttpClient hc = new HttpClient();
    Task<HttpResponseMessage> task1 = null;

    //call web api
    task1 = hc.PostAsJsonAsync<string> 
        ("http://10.5.72.172:108/api/vbaemail", "abc");
}
http.Open "POST", "http://10.5.72.172:108/api/vbaemail", True

而是 True 设置 False

I was able to get it to work by surrounding the string with single quotes. The problem is I can't use single quotes anywhere in the body being passed to the web api, although there's probably a way to escape them. In our case it's not a big deal, we're just trying to patch some old vba programs that are going away eventually.

Sub Test()

    Dim http As New MSXML2.XMLHTTP60
   
    http.Open "POST", "http://10.5.72.172:108/api/vbaemail", True

    http.SetRequestHeader "Content-type", "application/json"
    
    Call http.send("'" + strJson + "'")  
   
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM