1. 程式人生 > 其它 >.NET Core(C#) POST JSON資料和Form表單的方法及示例程式碼

.NET Core(C#) POST JSON資料和Form表單的方法及示例程式碼

本文主要.NET Core(C#)中,通過後臺程式碼提交JSON格式,提交Form(application/x-www-form-urlencoded或multipart/form-data)表單資料請求的方法,以及相關的示例程式碼。

1、POST提交JSON格式資料

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
    string json = "{\"user\":\"test\"," +
                  "\"password\":\"bla\"}";
    streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
}

相關文件.Net(C#)後臺傳送Get和Post請求的幾種方法總結

2、POST提交Form表單資料

1) type為"application/x-www-form-urlencoded"型別的表單

/// <summary>
/// 執行POST請求
/// </summary>
/// <param name="url"></param>
/// <param name="postData"></param>
/// <param name="contentType">application/xml、application/json、application/text、application/x-www-form-urlencoded</param>
/// <param name="headers">填充訊息頭</param>        
/// <returns></returns>
public static string HttpPost(string url, string paramData, Dictionary<string, string> headers = null, string contentType = "application/json", int timeOut = 30)
{
    using (HttpClient client = new HttpClient())
    {
        if (headers != null)
        {
            foreach (var header in headers)
                client.DefaultRequestHeaders.Add(header.Key, header.Value);
        }
        using (HttpContent httpContent = new StringContent(paramData, Encoding.UTF8))
        {
            if (contentType != null)
                httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
            HttpResponseMessage response = client.PostAsync(url, httpContent).Result;
            return response.Content.ReadAsStringAsync().Result;
        }
    }
}

2) type為"multipart/form-data"型別的表單

public async Task<string> UploadFile(string filePath)
{
    if (string.IsNullOrWhiteSpace(filePath))
    {
        throw new ArgumentNullException(nameof(filePath));
    }
    if (!File.Exists(filePath))
    {
        throw new FileNotFoundException($"File [{filePath}] not found.");
    }
    using var form = new MultipartFormDataContent();
    using var fileContent = new ByteArrayContent(await File.ReadAllBytesAsync(filePath));
    fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
    form.Add(fileContent, "file", Path.GetFileName(filePath));
    //表單中其它引數
    form.Add(new StringContent("789"), "userId");
    form.Add(new StringContent("some comments"), "comment");
    form.Add(new StringContent("true"), "isPrimary");
    var response = await _httpClient.PostAsync($"{_url}/api/files", form);
    response.EnsureSuccessStatusCode();
    var responseContent = await response.Content.ReadAsStringAsync();
    var result = JsonSerializer.Deserialize<FileUploadResult>(responseContent);
    _logger.LogInformation("Uploading is complete.");
    return result.Guid;
}

轉自:
.NET Core(C#) POST JSON資料和Form表單的方法及示例程式碼-CJavaPy