這是我的控制器 - 使用webApi框架4.6.1。它正確註冊,但是當我從我的.net core1.1應用程序發送ajax請求時,我在get和post方法上都得到了404錯誤。從.net核心應用程序調用時找不到web api路徑
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調用。 – mason
你能從瀏覽器中找到終點嗎? – InitLipton
您是否在webapi和core之間使用相同的端口(默認值爲5000)? –