简体   繁体   English

将JSON发布到Azure网站

[英]Post JSON to Azure website

I have a string that uses JsonTextWriter to create a JSON formatted-string. 我有一个使用JsonTextWriter创建JSON格式化字符串的字符串。 How do I interact with it if I want to store it in an Azure website? 如果要将其存储在Azure网站中如何与之交互? I was thinking of using an httpWebRequest like 我正在考虑使用类似的httpWebRequest

 string webAddr = "http://{url to website}/test.json";
 HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
 httpWebRequest.ContentType = "application/json; charset=utf-8";
 httpWebRequest.Method = "POST"; 

 StringWriter strwriter = new StringWriter();
 JsonTextWriter writer = new JsonTextWriter(strwriter);
 writer.WriteStartObject();
 writer.WritePropertyName("id");
 writer.WriteValue(v.id);
 writer.WriteEndObject();

 using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
    {
        string json = strwriter.ToString();

        streamWriter.Write(json);
    }

But I can't seem to figure out how to actually post the JSON to a file. 但是我似乎无法弄清楚如何将JSON实际发布到文件中。 Am I missing anything? 我有什么想念的吗?

I think that it would be fine to store on the local storage of the VM/website to avoid a CORS issue, unless there is something that Blob storage would benefit over local storage. 我认为最好将其存储在VM /网站的本地存储中,以避免发生CORS问题,除非Blob存储比本地存储有优势。

You're part way there, next you need to actually dispatch the request: 您正在那里,接下来您需要实际分发请求:

HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();

And you can read through the returned body (if required): 您可以阅读返回的正文(如果需要):

using (httpWebResponse)
{
    StreamReader reader = new StreamReader(httpWebResponse.GetResponseStream());

    string response_body = reader.ReadToEnd();
}

Assuming you just wanted to dump the body to the file system (for arguments sake): 假设您只是想将主体转储到文件系统中(出于参数考虑):

using (httpWebResponse)
{
    ...

    using (var file = new FileStream("some\path\to\file.json",FileMode.Create,FileAccess.Write,FileShare.None))
    {
        StreamWriter writer = new StreamWriter(file,Encoding.UTF8);

        writer.Write(response_body);
        writer.Flush();
    }
}

However this won't work for non VM websites, for that you'd probably have to shun the file off to blob storage. 但是,这不适用于非VM网站,因为您可能不得不将文件避开到Blob存储中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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