如何从 javascript 调用我的 WebApi?
How can I call my WebApi from javascript?
我需要使用 javascript.
调用 webapi POST 方法
该方法接受一个模型。我能够从 POSTMAN 正确调用此方法,还可以看到数据库中的条目。
// POST api/values
[HttpPost]
public IHttpActionResult Post([FromBody] Models.InspectionPhoto iPhoto)
{
try
{
Debug.WriteLine("In post method");
var connstr = ConfigurationManager.ConnectionStrings["MyDbConnection"].ConnectionString;
Debug.WriteLine("initializing dbconnection");
var db = new RamDbDataContext(connstr);
Debug.WriteLine("mapping entity");
var inspectionPhoto = new DBLinq.InspectionPhoto
{
InspectionId = iPhoto.InspectionId,
InsertEmployee = iPhoto.Employee,
UpdateEmployee = iPhoto.Employee,
Photo = iPhoto.Data,
InspectionCategoryId = 8,
UpdateDate = DateTime.UtcNow,
InsertDate = DateTime.UtcNow
};
Debug.WriteLine("inserting entity");
db.InspectionPhotos.InsertOnSubmit(inspectionPhoto);
db.SubmitChanges();
Debug.WriteLine("done inserting entity");
int id = inspectionPhoto.Id;
return Ok(id);
}
catch(Exception ex)
{
Debug.WriteLine(ex.Message);
return Ok(-1);
}
}
当我尝试从 javascript 调用此方法时,它没有到达端点。我试过 CORS 设置,但没什么帮助。
这是我的 javascript 调用此方法的代码。
<script>
function callwebapi()
{
jsonIn = document.getElementById("mytext").value;
console.log('++As you are+++');
console.log(jsonIn);
console.log('++As you are+++');
const uri = 'https://localhost:44304/api/values';
fetch(uri, {
method: 'POST',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'User-Agent': 'PostmanRuntime/7.28.4'
},
body: jsonIn
})
.then(result => console.log(result.status))
.then(response => response.json())
.then(response => console.log('Success: ', response))
.catch(error => console.error('Failure: ', error));
}
</script>
<textarea id="mytext">
{"Id": -1, "InspectionId": 95, "CategoryId": 9, "Employee": "Roger Moore", "Data": null}
</textarea>
<button onclick="callwebapi();">Click this and send your data!</button>
我在 chrome 浏览器控制台中得到的错误是
TypeError: Failed to fetch
at callwebapi (About:89:13)
at HTMLButtonElement.onclick (About:110:37)
我创建了一个 ASP .NET Web 应用程序并开始使用 Web 表单项目。
客户端代码是在 About.cshtml 页面上创建的。
我最终需要将此代码合并到现有应用程序中。
我该如何修复此错误并成功调用?
编辑:
邮递员呼叫请求。这就是我从 Postman 拨打电话的方式。
我必须更改客户端代码和服务器端代码才能完成这项工作。
对客户端代码的更改
function takepicture() {
var context = canvas.getContext('2d');
if (width && height) {
canvas.width = width;
canvas.height = height;
context.drawImage(video, 0, 0, width, height);
var data = canvas.toDataURL('image/png');
photo.setAttribute('src', data);
console.log(data);
console.log('+++++++++++++++++++JUST NOT DATA++++++++++++++');
var dataPart = data.split(',')[1];
console.log('+++++++++++++++++++JUST DATA++++++++++++++');
console.log(dataPart);
console.log('+++++++++++++++++++JUST DATA++++++++++++++');
class nemo {
constructor(Id, InspectionId, CategoryId, Employee, Data) {
this.Id = -1;
this.InspectionId = 95;
this.CategoryId = 8;
this.Employee = 'Scanner01';
this.Data = dataPart;
}
}
const instanceofnemo = new nemo();
callwebapi(instanceofnemo);
} else {
clearphoto();
}
}
function callwebapi(someclass)
{
console.log(JSON.stringify(someclass));
const uri = 'https://localhost:44304/api/values';
fetch(uri, {
method: 'POST',
mode:'no-cors',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(someclass)
})
.then(response => response.json())
.catch(error => console.error('Some Failure Occurred.', error));
}
服务器端代码更改:
[System.Web.Http.HttpPost]
public IHttpActionResult Post([FromBody] Models.InspectionPhoto iPhoto)
{
try
{
Debug.WriteLine("In post method");
var connstr = ConfigurationManager.ConnectionStrings["RAMSESTest_2021_11_02ConnectionString"].ConnectionString;
Debug.WriteLine("initializing dbconnection");
var db = new RamDbDataContext(connstr);
Debug.WriteLine("mapping entity");
var inspectionPhoto = new DBLinq.InspectionPhoto
{
InspectionId = iPhoto.InspectionId,
InsertEmployee = iPhoto.Employee,
UpdateEmployee = iPhoto.Employee,
Photo = iPhoto.Data,
InspectionCategoryId = iPhoto.CategoryId,
UpdateDate = DateTime.UtcNow,
InsertDate = DateTime.UtcNow
};
Debug.WriteLine("inserting entity");
db.InspectionPhotos.InsertOnSubmit(inspectionPhoto);
db.SubmitChanges();
Debug.WriteLine("done inserting entity");
int id = inspectionPhoto.Id;
HttpResponseMessage responseMessage = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
responseMessage.Headers.Add("Access-Control-Allow-Origin", "*");
responseMessage.Content =new StringContent(id.ToString(), Encoding.UTF8, "application/json");
return ResponseMessage(responseMessage);
}
catch(Exception ex)
{
Debug.WriteLine(ex.Message);
return Ok(-1);
}
}
//WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.EnableCors();
// Web API routes
config.MapHttpAttributeRoutes();
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
我需要使用 javascript.
调用 webapi POST 方法该方法接受一个模型。我能够从 POSTMAN 正确调用此方法,还可以看到数据库中的条目。
// POST api/values
[HttpPost]
public IHttpActionResult Post([FromBody] Models.InspectionPhoto iPhoto)
{
try
{
Debug.WriteLine("In post method");
var connstr = ConfigurationManager.ConnectionStrings["MyDbConnection"].ConnectionString;
Debug.WriteLine("initializing dbconnection");
var db = new RamDbDataContext(connstr);
Debug.WriteLine("mapping entity");
var inspectionPhoto = new DBLinq.InspectionPhoto
{
InspectionId = iPhoto.InspectionId,
InsertEmployee = iPhoto.Employee,
UpdateEmployee = iPhoto.Employee,
Photo = iPhoto.Data,
InspectionCategoryId = 8,
UpdateDate = DateTime.UtcNow,
InsertDate = DateTime.UtcNow
};
Debug.WriteLine("inserting entity");
db.InspectionPhotos.InsertOnSubmit(inspectionPhoto);
db.SubmitChanges();
Debug.WriteLine("done inserting entity");
int id = inspectionPhoto.Id;
return Ok(id);
}
catch(Exception ex)
{
Debug.WriteLine(ex.Message);
return Ok(-1);
}
}
当我尝试从 javascript 调用此方法时,它没有到达端点。我试过 CORS 设置,但没什么帮助。
这是我的 javascript 调用此方法的代码。
<script>
function callwebapi()
{
jsonIn = document.getElementById("mytext").value;
console.log('++As you are+++');
console.log(jsonIn);
console.log('++As you are+++');
const uri = 'https://localhost:44304/api/values';
fetch(uri, {
method: 'POST',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'User-Agent': 'PostmanRuntime/7.28.4'
},
body: jsonIn
})
.then(result => console.log(result.status))
.then(response => response.json())
.then(response => console.log('Success: ', response))
.catch(error => console.error('Failure: ', error));
}
</script>
<textarea id="mytext">
{"Id": -1, "InspectionId": 95, "CategoryId": 9, "Employee": "Roger Moore", "Data": null}
</textarea>
<button onclick="callwebapi();">Click this and send your data!</button>
我在 chrome 浏览器控制台中得到的错误是
TypeError: Failed to fetch at callwebapi (About:89:13) at HTMLButtonElement.onclick (About:110:37)
我创建了一个 ASP .NET Web 应用程序并开始使用 Web 表单项目。 客户端代码是在 About.cshtml 页面上创建的。
我最终需要将此代码合并到现有应用程序中。 我该如何修复此错误并成功调用?
编辑: 邮递员呼叫请求。这就是我从 Postman 拨打电话的方式。
我必须更改客户端代码和服务器端代码才能完成这项工作。
对客户端代码的更改
function takepicture() {
var context = canvas.getContext('2d');
if (width && height) {
canvas.width = width;
canvas.height = height;
context.drawImage(video, 0, 0, width, height);
var data = canvas.toDataURL('image/png');
photo.setAttribute('src', data);
console.log(data);
console.log('+++++++++++++++++++JUST NOT DATA++++++++++++++');
var dataPart = data.split(',')[1];
console.log('+++++++++++++++++++JUST DATA++++++++++++++');
console.log(dataPart);
console.log('+++++++++++++++++++JUST DATA++++++++++++++');
class nemo {
constructor(Id, InspectionId, CategoryId, Employee, Data) {
this.Id = -1;
this.InspectionId = 95;
this.CategoryId = 8;
this.Employee = 'Scanner01';
this.Data = dataPart;
}
}
const instanceofnemo = new nemo();
callwebapi(instanceofnemo);
} else {
clearphoto();
}
}
function callwebapi(someclass)
{
console.log(JSON.stringify(someclass));
const uri = 'https://localhost:44304/api/values';
fetch(uri, {
method: 'POST',
mode:'no-cors',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(someclass)
})
.then(response => response.json())
.catch(error => console.error('Some Failure Occurred.', error));
}
服务器端代码更改:
[System.Web.Http.HttpPost]
public IHttpActionResult Post([FromBody] Models.InspectionPhoto iPhoto)
{
try
{
Debug.WriteLine("In post method");
var connstr = ConfigurationManager.ConnectionStrings["RAMSESTest_2021_11_02ConnectionString"].ConnectionString;
Debug.WriteLine("initializing dbconnection");
var db = new RamDbDataContext(connstr);
Debug.WriteLine("mapping entity");
var inspectionPhoto = new DBLinq.InspectionPhoto
{
InspectionId = iPhoto.InspectionId,
InsertEmployee = iPhoto.Employee,
UpdateEmployee = iPhoto.Employee,
Photo = iPhoto.Data,
InspectionCategoryId = iPhoto.CategoryId,
UpdateDate = DateTime.UtcNow,
InsertDate = DateTime.UtcNow
};
Debug.WriteLine("inserting entity");
db.InspectionPhotos.InsertOnSubmit(inspectionPhoto);
db.SubmitChanges();
Debug.WriteLine("done inserting entity");
int id = inspectionPhoto.Id;
HttpResponseMessage responseMessage = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
responseMessage.Headers.Add("Access-Control-Allow-Origin", "*");
responseMessage.Content =new StringContent(id.ToString(), Encoding.UTF8, "application/json");
return ResponseMessage(responseMessage);
}
catch(Exception ex)
{
Debug.WriteLine(ex.Message);
return Ok(-1);
}
}
//WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.EnableCors();
// Web API routes
config.MapHttpAttributeRoutes();
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}