【发布时间】:2019-01-25 14:23:41
【问题描述】:
我正在 ASP.Net 上上课,我需要制作一个进行计算的 Web Api。我可以让它为 Addition 工作,但是当我尝试执行其他功能时,我无法让它们工作。我确定这是我想念的简单的东西,但我不知道。有人可以给我一些帮助吗?
型号:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebAPICalc.Models
{
public class Calc
{
public float Add(float fn, float sn)
{ return (sn + fn); }
public float Sub(float fn, float sn)
{ return (sn - fn); }
}
}
控制器:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebAPICalc.Models;
namespace WebAPICalc.Controllers
{
public class CalcController : ApiController
{
Calc oCalc = new Calc();
[Route("api/calc/add/{paramOne}/{paramTwo}")]
public float Get(float paramOne, float paramTwo)
{
return oCalc.Add(paramOne, paramTwo);
}
[Route("api/calc/sub/{paramOne}/{paramTwo}")]
public IHttpActionResult GetSub(float paramOne, float paramTwo)
{
return Ok(oCalc.Sub(paramOne, paramTwo));
}
}
}
查看:
<h2>Mycalc</h2>
<input type="text" id="fn" size="5" />
<input type="text" id="sn" size="5" />
<input type="text" id="tn" size="5" />
<input type="button" value="add" onclick="add();" />
<input type="button" value="sub" onclick="sub();" />
<script>
function add() {
alert("here api/calc/add/ " + fn.value + " /" + sn.value)
$.ajax({
url: "api/calc/add/" + fn.value + "/" + sn.value,
//url: "api/calc/add/5/7",
cache: false,
success: function (html) {
alert(html)
tn.value = html
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
function sub() {
alert("here api/calc/sub/ " + fn.value + " /" + sn.value)
$.ajax({
url: "api/calc/sub/" + fn.value + "/" + sn.value,
//url: "api/calc/sub/5/7",
cache: false,
success: function (html) {
alert(html)
tn.value = html
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
</script>
【问题讨论】:
-
I can't get them to work是什么意思?您面临什么问题? -
如果我添加减法,我会在返回任何一个按钮时出现 404 错误。如果我只是做加法,它就可以工作,并且我得到没有 404 的结果。所以我不确定添加减法按钮和要在脚本中调用的函数后有什么区别
标签: c# jquery asp.net-mvc asp.net-web-api asp.net-ajax