c# - Ajax 调用 Web API 成功但 C# 调用 Web API 404 未找到
问题描述
我有这些网络 API 方法:
[System.Web.Http.RoutePrefix("api/PurchaseOrder")]
public class PurchaseOrderController : ApiController
{
private static ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
[System.Web.Http.Route("PagingCriticalPart")]
[System.Web.Http.HttpPost]
public JsonResult PagingCriticalPart([FromBody] Helper.DataTablesBase model)
{
logger.Info("PagingCriticalPart");
JsonResult jsonResult = new JsonResult();
try
{
if (model == null) { logger.Info("model is null."); }
int filteredResultsCount;
int totalResultsCount;
var res = BLL.PurchaseOrderHandler.PagingCriticalPart(model, out filteredResultsCount, out totalResultsCount);
var result = new List<Models.T_CT2_CriticalPart>(res.Count);
foreach (var s in res)
{
// simple remapping adding extra info to found dataset
result.Add(new Models.T_CT2_CriticalPart
{
active = s.active,
createBy = s.createBy,
createdDate = s.createdDate,
id = s.id,
modifiedBy = s.modifiedBy,
modifiedDate = s.modifiedDate,
partDescription = s.partDescription,
partNumber = s.partNumber
});
};
jsonResult.Data = new
{
draw = model.draw,
recordsTotal = totalResultsCount,
recordsFiltered = filteredResultsCount,
data = result
};
return jsonResult;
}
catch (Exception exception)
{
logger.Error("PagingCriticalPart", exception);
string exceptionMessage = ((string.IsNullOrEmpty(exception.Message)) ? "" : Environment.NewLine + Environment.NewLine + exception.Message);
string innerExceptionMessage = ((exception.InnerException == null) ? "" : ((string.IsNullOrEmpty(exception.InnerException.Message)) ? "" : Environment.NewLine + Environment.NewLine + exception.InnerException.Message));
jsonResult.Data = new
{
draw = model.draw,
recordsTotal = 0,
recordsFiltered = 0,
data = new { },
error = exception.Message
};
return jsonResult;
}
}
[System.Web.Http.Route("UploadRawMaterialData")]
[System.Web.Http.HttpPost]
public JsonResult UploadRawMaterialData(string rawMaterialSupplierData)
{
JsonResult jsonResult = new JsonResult();
jsonResult.Data = new
{
uploadSuccess = true
};
return jsonResult;
}
}
使用ajax调用PagingCriticalPart
时,没有问题。
"ajax": {
url: 'http://localhost/ControlTower2WebAPI/api/PurchaseOrder/PagingCriticalPart',
type: 'POST',
contentType: "application/json",
data: function (data) {
//debugger;
var model = {
draw: data.draw,
start: data.start,
length: data.length,
columns: data.columns,
search: data.search,
order: data.order
};
return JSON.stringify(model);
},
failure: function (result) {
debugger;
alert("Error occurred while trying to get data from server: " + result.sEcho);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
debugger;
alert("Error occurred while trying to get data from server!");
},
dataSrc: function (json) {
//debugger;
for (key in json.Data) { json[key] = json.Data[key]; }
delete json['Data'];
return json.data;
}
}
但是当UploadRawMaterialData
从 c# 调用时,它得到错误:404 未找到。
var data = Newtonsoft.Json.JsonConvert.SerializeObject(rawMaterialVendorUploads);
string apiURL = @"http://localhost/ControlTower2WebAPI/api/PurchaseOrder/UploadRawMaterialData";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiURL);
request.UseDefaultCredentials = true;
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = data.Length;
using (Stream webStream = request.GetRequestStream())
using (StreamWriter requestWriter = new StreamWriter(webStream, System.Text.Encoding.ASCII))
{
requestWriter.Write(data);
}
try
{
WebResponse webResponse = request.GetResponse();
using (Stream webStream = webResponse.GetResponseStream() ?? Stream.Null)
using (StreamReader responseReader = new StreamReader(webStream))
{
string response = responseReader.ReadToEnd();
}
}
catch (Exception exception)
{
}
使用邮递员返回类似的错误:
{
"Message": "No HTTP resource was found that matches the request URI 'http://localhost/ControlTower2WebAPI/api/PurchaseOrder/UploadRawMaterialData'.",
"MessageDetail": "No action was found on the controller 'PurchaseOrder' that matches the request."
}
但是如果我用邮递员这样称呼它,没问题:
http://localhost/ControlTower2WebAPI/api/PurchaseOrder/UploadRawMaterialData?rawMaterialSupplierData=test
我错过了什么?
解决方案
在您的方法签名中,UploadRawMaterialData
您缺少该[FromBody]
属性。正文中包含数据的所有POST
请求都需要这个
推荐阅读
- java - 无法在控制台输出中打印 SQL 语句
- go - 如何编写一个 golang 验证函数,以便客户端能够优雅地处理?
- laravel - Laravel Nova 自定义字段,防止按“Enter”键提交表单
- google-cloud-platform - 哪个是首选 - gcloud sdk 或 gcloud api?
- c# - 我可以使用这段旧代码来更改富文本框中一行的文本颜色吗?
- node.js - 如何将 JSON 文件导出到 ExpressJS 中的 URL,然后还能够从该 URL 导入 JSON 文件?
- visual-studio-2017 - 检测到包降级:Microsoft.EntityFrameworkCore.SqlServer 从 2.2.6 到 2.2.4
- c - Packing a Float (IEEE-754) into uint64_t 代码的规范化部分
- python - 有人可以向我解释 map_coordinates 如何在 n 维数据集上工作吗?
- c - 带有 Frama-C 和 Eva 的动态阵列