我正在处理我的项目,其中使用 Asp.net 与 C# 和 Javascript。 我用 c# 设置了 Controller ,它接受一个对象和两个附加变量。这是一个 HttpPost 请求,在我添加其他变量之前它工作正常。我在 fetch json 函数中使用了 console.log 来检查我是否真正获得了所需的值。 这种获取对于 postman 来说工作得很好!
我还尝试过在 Rented 对象上交换位置,以便它位于最后一个位置(如果获取的主体也是最后发送的),但它不起作用。 这是我在 chrome 浏览器中调用该函数时得到的结果: https://localhost:44363/rent/save?movieId=2&maxRents=3状态 = 400
感觉我在这里遗漏了一些非常基本的东西,也许你不能在请求中同时发送变量和正文?
这是 Controller 代码:
[HttpPost("save")]
public ActionResult<Rented> SaveRent(Rented newLoan, int movieId, int maxRents)
{
var amountOfRent = _appDbContext.Rents.Where(m => m.MovieId == movieId);
if (maxRents <= amountOfRent.Count())
{
_appDbContext.Rents.Add(newLoan);
_appDbContext.SaveChanges();
return newLoan;
}
else
{
return BadRequest();
}
}
这是 Fetch 函数:
function addToStudio(element) {
var movieId = element.id;
var studioId = element.value;
var maxRents = element.name;
var newId = Number(movieId);
var newStudioId = Number(studioId);
console.log(maxRents);
fetch('https://localhost:44363/rent/save?movieId=' + movieId + '&maxRents=' + maxRents, {
method: 'POST',
body: JSON.stringify({
studioId: newStudioId,
movieId: newId
}),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.catch(err => console.error("response-error", err))
.then(response => response.json())
.then(json => console.log(json))
.catch(err => console.error("json error", err))
container.innerHTML = `<h1>Saved</h1>`
}
最佳答案
我在这里看到几个问题:
- 您在请求正文和网址查询中都使用了。
- 您在控制方法签名中缺少一些重要属性。
我个人总是尝试使用单一方法(正文或 URL 查询)。我发现它使代码更具可读性并且不易出现错误。
首先,决定如何传递数据:
- 通过请求正文
- 在 URL 查询中
- 混合方法
然后相应地编写您的方法。
在体内
最简单的方法是将您的信息封装在 .Net 对象中,并在 JavaScript 中对其字段进行 Jsonify:
public class RentDetails
{
public int MovieId {get; set;}
public int MaxRents {get; set;}
public Studio {get; set;} // you can also use objects, deserializing the Json will fill them as well.
}
然后,您需要在方法的签名中指定您将在请求正文中接收 RentDetails
。
[HttpPost("save")]
public ActionResult<Rented> SaveRent([FromBody] RentDetails rentDetails) { ... }
最后,您希望 Jsonified 主体反射(reflect)应该接收的对象(注意字段名称):
const request = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
movieId : movieID,
maxRent : maxRent,
studio:
{
// nested fields for nested objects
}
})
};
如果您按照这些步骤操作,您的 Controller 将自动将正文中的 json 反序列化为对象,然后您就可以使用它了。
在 URL 查询中
这更容易处理,但可能会变得困惑。
按照您已经做的方式连接 javascript 中的字段:
const link = baseLink.concat('?movieId=', movieId, '&maxRent=', maxRent, ...);
const result = await fetch(link); // no request is needed here, you already have all you need.
然后从 Controller 访问这些字段:
[HttpPost("save")]
public ActionResult<Rented> SaveRent() //<- no parameters are needed here
{
var allUrlKeyValues = HttpUtility.ParseQueryString(Request.QueryString.Value);
var movieId = int.Parse(allUrlKeyValues["movieId"]);
var maxRent = int.Parse(allUrlKeyValues["maxRent"]);
....
// as you see you can only pass strings in this way
}
混合方法
当然,您可以选择混合方法,只需使用上面代码的组合即可。
请注意,越简单越好;)。
关于javascript - 使用 Fetch 发送 url 中的变量和 Body 中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60015203/