首页 > 解决方案 > 我无法使用 umbraco 项目在 WebAPI 中使用 Get 方法

问题描述

我很难打 webapi 动作。我在控制台中收到 500 错误并且未访问 api。

这是我的ajax调用:

function getProducts() {
    var response;
    $.getJSON("/api/Product")
        .done(function (data) {
            response = $.map(data,
                function (item) {
                    return { label: item.Name + ' (' + item.Code + ')' };
                });
        });
    return response;
};

ajax 没有命中。请求跳过getJsoncall 并返回undefined response

这是我的 api 控制器方法:

public class ProductController : ApiController {

    // GET api/<controller>
        public IEnumerable<ProductModel> ProductList()
        {
            ProductSearcher searcher = new ProductSearcher();
            return searcher.GetResults();
        }
    }

在我定义的配置中:

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

邮递员回来Object reference not set to an instance of an object了,但它甚至都没有击中ProductList

我已选择运行多个项目 - 我的应用程序启动项目和 web api 项目。

这是错误堆栈跟踪-在我看来,umbraco 确实在寻找路由,而我需要路由到非 umbraco api:

[NullReferenceException: Object reference not set to an instance of an object.]
   Umbraco.Web.Routing.ContentLastChanceFinderByNotFoundHandlers.HandlePageNotFound(PublishedContentRequest docRequest) +152
   Umbraco.Web.Routing.ContentLastChanceFinderByNotFoundHandlers.TryFindContent(PublishedContentRequest docRequest) +10
   Umbraco.Web.Routing.PublishedContentRequestEngine.HandlePublishedContent() +529
   Umbraco.Web.Routing.PublishedContentRequestEngine.FindPublishedContentAndTemplate() +250
   Umbraco.Web.Routing.PublishedContentRequestEngine.PrepareRequest() +107
   Umbraco.Web.UmbracoModule.ProcessRequest(HttpContextBase httpContext) +361
   Umbraco.Web.UmbracoModule.&lt;Init&gt;b__8(Object sender, EventArgs e) +80
   System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +141
   System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +48
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously) +71

编辑

我将路由配置从更改apidataapi例如。routeTemplate:"dataapi/{controller}/{id}"所以它现在运行但仍然抛出错误:

405 Method not allowed

编辑 2

知道了!将方法名称从更改为ProductListGet现在可以使用

标签: asp.net-web-apiasp.net-web-api2umbracoumbraco7asp.net-web-api-routing

解决方案


您可以改用 UmbracoApiController 来确保 Umbraco 不会尝试将 URL 与内容匹配?然后控制器的路径将改为 /umbraco/api/yourcontroller,但一切都应该工作相同。查看https://our.umbraco.com/documentation/reference/routing/webapi/了解详情。


推荐阅读