【发布时间】:2017-11-18 03:56:05
【问题描述】:
这是我的控制器 - 使用 webApi 框架 4.6.1。它注册正确,但是当我从 .net core1.1 应用程序发送 ajax 请求时,get 和 post 方法都出现 404 错误。
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
public class MainController : ApiController
{
/// <summary>
/// ExistingItems - keep a list of all items that are currently in
the list and were not processed, for auditing.
/// </summary>
public List<XMLData.Struct> ExistingItems = new List<XMLData.Struct>
();
[Route("api/Main/GetMyList")]
[ActionName("GetMyList")]
[System.Web.Http.HttpGet]
public HttpResponseMessage GetMyList()
{
HttpResponseMessage resp = new HttpResponseMessage();
resp.StatusCode = HttpStatusCode.OK;
return resp;
}
/// <summary>
/// PostXMLFile - process the xml file on the server.
/// </summary>
/// <param name="value"></param>
[Route("api/Main/SaveXML/")]
[ActionName("SaveXml")]
[System.Web.Http.HttpPost]
public HttpResponseMessage SaveXml(string value)
{
List<XMLData.Struct> pageElements = ConvertToList(value);
var url = "/resource/BigBearNew.xml";
var path = System.Web.Hosting.HostingEnvironment.MapPath(url);
XmlDocument xDoc = new XmlDocument();
xDoc.Load(path);
foreach (var pge in pageElements)
{
if (!ElementExists(xDoc, pge))
{
AddAsNew(xDoc, pge);
};
}
HttpResponseMessage resp = new HttpResponseMessage();
resp.StatusCode = HttpStatusCode.OK;
return resp; // OK = 200
}
这是 .net core1.1 调用。我在 .net 核心项目中引用了 WebApi 项目。
function saveElementList()
{
$.ajax({
url: 'api/Main/SaveXml',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(elementNodes),
success: function (data) {
alert("Saved successfully");
}
});
}
function getList() {
$.ajax({
url: 'api/Main/GetMyList',
type: 'GET',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
// data: JSON.stringify(elementNodes),
success: function (data) {
alert("got list successfully");
}
});
}
我检查了控制器上的路由和属性,它们看起来是正确的。提前致谢。
【问题讨论】:
-
我看不出 .NET Core 在哪里适合。我在 .NET Framework 上看到了一个 Web API 2 应用程序,并且看到了一些 AJAX 调用。
-
你能从浏览器打到终点吗?
-
你是否在 webapi 和 core 之间使用相同的端口(默认为 5000)?
-
如果动作名称中有“GetMyList”,你确定在路由中需要它吗?
-
尝试从
[Route("api/Main/SaveXML/")]中删除结尾/?
标签: c# asp.net-web-api .net-core asp.net-web-api-routing