一、使用jQuery Ajax访问
(一)、表单传参( [FromForm])
数据类型:Object
ContenyType类型:application/x-www-form-urlencoded
1
var model = { name: "刘大大", age: 23, sex: true };
前台请求
var model = { name: "刘大大", age: 23, sex: true };
$.ajax({
url: "http://localhost:9001/API/Default/FormCall",
type: "POST",
async: true,
dataType: "json",
data: model,
contentType: "application/x-www-form-urlencoded",
success: function (data) {
console.log("data:");
console.log(data);
}
});
(二)、JSON字符串[FromBdy]
数据类型:Json
ContenyType类型:application/json
1
var json = '{"name":"刘大大","age":23,"sex":true}';
也可以使用JSON.stringify(Object)将Object转换为JSON字符串
前端请求
var model = { name: "刘大大", age: 23, sex: true };
$.ajax({
url: "http://localhost:9001/API/Default/BodyCall",
type: "POST",
async: true,
dataType: "json",
data: JSON.stringify(model),
contentType: "application/json",
success: function (data) {
console.log("data:");
console.log(data);
}
});
(三)、文件上传
建立FormData对象
数据类型:FromData
ContenyType类型false, //必须false才会避开jQuery对 formdata 的默认处理 processData类型: false, //必须false才会自动加上正确的Content-Type
html
1
<input type="file" multiple id="file" />
JS获取文件对象
var file = document.getElementById("file");
var files = file.files;
var formData = new FormData();
for (var i = 0; i < files.length; i++) {
formData.append(files[i].name, files[i]);
}
formData.append("name", "刘大大");//可追加参数
AJAX请求
$.ajax({
url: "http://localhost:9001/API/Default/Upload",
type: "POST",
async: true,
dataType: "json",
data: formData,
contentType: false,
processData: false,
success: function (data) {
console.log(data);
}
});
完整HTML源码
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>
<div>
<input type="button" id="fromform" value="Form传参" /><hr />
<input type="button" id="frombody" value="Body传参" /><hr />
<input type="file" multiple id="file" name="上传文件" /><hr />
</div>
<script src="https://cdn.bootcss.com/jquery/3.3.0/jquery.js"></script>
<script>
/**
* FromForm
* */
var fromform = document.getElementById("fromform");
$(fromform).click(function () {
var url = 'http://localhost:9001/API/Default/FormCall';
var model = { name: "刘大大", age: 23, sex: true };
$.ajax({
url: url,
type: "POST",
async: true,
data: model,
contentType: "application/x-www-form-urlencoded",
success: function (data) {
console.log(data);
alert(JSON.stringify(data));
},
error: function (result) {
console.log(result);
}
});
});
/**
* FromBody
* */
$('#frombody').click(function () {
var url = 'http://localhost:9001/API/Default/BodyCall';
var json = '{"name":"刘大大","age":23,"sex":true}';
$.ajax({
url: url,
type: "POST",
async: true,
data: json,
contentType: "application/json",
success: function (data) {
console.log(data);
alert(JSON.stringify(data));
},
error: function (result) {
console.log(result);
}
});
});
/**
* FormData
* */
var file = document.getElementById("file");
file.onchange = function () {
var file = document.getElementById("file");
var files = file.files;
var formData = new FormData();
for (var i = 0; i < files.length; i++) {
formData.append(files[i].name, files[i]);
}
formData.append("name", "刘大大");
var isUploadByJs = true;
var url = isUploadByJs ? 'http://localhost:9001/API/Default/Upload' : 'http://localhost:9002/Home/Upload';
$.ajax({
url: url,
type: "POST",
async: true,
dataType: "json",
data: formData,
contentType: false, //必须false才会避开jQuery对 formdata 的默认处理
processData: false, //必须false才会自动加上正确的Content-Type
headers: { ReadTime: Date.now() },
beforeSend: function (xhr) {
xhr.setRequestHeader('Author', 'liudada');
},
success: function (data) {
console.log(data);
alert(JSON.stringify(data));
},
error: function (result) {
console.log(result);
}
});
}
</script>
二、使用C#后台访问
(一)、Get访问
var url = "http://localhost:57954/API/Default/Test";
using (var client = new HttpClient(new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip }))
{
var taskResponse = client.GetAsync(url);
taskResponse.Wait();
if (taskResponse.IsCompletedSuccessfully)
{
var taskStream = taskResponse.Result.Content.ReadAsStreamAsync();
taskStream.Wait();
using (var reader = new StreamReader(taskStream.Result))
{
jsonString = reader.ReadToEnd();
}
}
}
(二)、Post访问
var url = "http://localhost:57954/API/Default/BodyCall";
var data = new {name="刘大大",age=23,sex=true };
using (var client = new HttpClient(new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip }))
{
var jsonToSend = JsonConvert.SerializeObject(data, Formatting.None, new IsoDateTimeConverter());
var body = new StringContent(jsonToSend, Encoding.UTF8, "application/json");
var taskResponse = client.PostAsync(url, body);
taskResponse.Wait();
if (taskResponse.IsCompletedSuccessfully)
{
var taskStream = taskResponse.Result.Content.ReadAsStreamAsync();
taskStream.Wait();
using (var reader = new StreamReader(taskStream.Result))
{
jsonString = reader.ReadToEnd();
}
}
}
(三)、上传文件
/// <summary>
/// 上传文件
/// </summary>
/// <returns></returns>
[RequestSizeLimit(1_073_741_824)]
public IActionResult Upload()
{
var url = "http://localhost:9001/Api/Default/Upload";
var data = new MultipartFormDataContent();
if (Request.HasFormContentType)
{
var request = Request.Form.Files;
foreach (var item in request)
{
data.Add(new StreamContent(item.OpenReadStream()), item.Name, item.FileName);
}
foreach (var item in Request.Form)
{
data.Add(new StringContent(item.Value), item.Key);
}
}
string jsonString = string.Empty;
using (var client = new HttpClient(new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip }))
{
var taskResponse = client.PostAsync(url, data);
taskResponse.Wait();
if (taskResponse.IsCompletedSuccessfully)
{
var taskStream = taskResponse.Result.Content.ReadAsStreamAsync();
taskStream.Wait();
using (var reader = new StreamReader(taskStream.Result))
{
jsonString = reader.ReadToEnd();
}
}
}
return new JsonResult(jsonString);
}
WebHelper