Skip to main content
 首页 » 编程设计

c#之AngularJS Controller 找不到 C# Controller

2024年02月05日26EasonJim

希望大家帮帮我。

我有一个简单的项目仍处于起步阶段,但无法让 AngularJS Controller (ingredientAdmin.controller) 找到我的 C# API Controller 。

我收到错误:404/未找到:请求 URL:http://localhost:31021/api/ingredientAdmin/PostIngredient/

我的 AngularJS Controller 和 C# Controller 在不同的项目中,我在我的 AngularJS 项目中引用了我的 C# Controller 项目。

我也尝试过各种拼写等,但认为我可能遗漏了一些东西。

这是我的 AngularJS Controller :ingredientAdminController:

(function () { 
    "use strict"; 
    var controllerId = 'admin'; 
 
    angular 
        .module('app.ingredientAdmin') 
        .controller('ingredientAdminController', ingredientAdminController, controllerId); 
 
    ingredientAdminController.$inject = ['$http', '$scope', 'common']; 
 
    function ingredientAdminController($http, $scope, common) { 
        var vm = $scope; 
        vm.formSubmmision = true; 
        vm.title = 'Ingredients Admin'; 
        vm.ingredientData = null; 
        vm.save = save; 
 
        var getLogFn = common.logger.getLogFn; 
        var log = getLogFn(controllerId); 
 
        activate(); 
 
        function activate() { 
            common.activateController([], controllerId) 
                .then(function () { log('Activated Admin View'); }); 
        } 
 
        // Save 
 
        function save() { 
            if (vm.formIngredientsAdmin.$valid) { 
                postNewData(); 
            } 
            else { 
                logger.error('Error: Validation failed. Please correct data and try again'); 
                vm.formSubmmision = false; 
            } 
        } 
 
        function postNewData() { 
            //prepare data  
            var data = { 
                IngredientId: 0, 
                IngredientName: vm.NewIngredient.IngredientName, 
                IngredientDescription: vm.NewIngredient.IngredientDescription 
            } 
 
 
            $http.post('/api/ingredientAdmin/PostIngredient/', data) 
                .then(postDataComplete) 
                .catch(getDataFailed); 
 
            function postDataComplete(response) { 
                vm.NewIngredient = null; 
                vm.formSubmmision = true; 
                vm.formIngredientsAdmin.$setPristine(); 
                vm.formIngredientsAdmin.$setUntouched(); 
                return vm.NewIngredient; 
            } 
 
            function getDataFailed(error) { 
                log('Failed to create new Ingredient ' + error.data.Message); 
                return; 
            } 
 
        } 
 
 
    }; 
 
 
} 
)(); 

这是我的 C# Controller :IngredientAdminController:

using System.Net; 
using System.Net.Http; 
using System.Web.Http; 
using RecipeManager.Models; 
using RecipeManager.DTO; 
using RecipeManger.Common; 
 
namespace RecipeManager.Controllers.Api 
{ 
    public class IngredientAdminController : ApiController 
    { 
        private RecipeManager.DTO.IngredientAdminDTO dto = new IngredientAdminDTO(); 
 
        [HttpPost] 
        public HttpResponseMessage PostIngredient(Ingredient ingredient) 
        { 
            try 
            { 
                CommandResult<Ingredient> result = dto.CreateIngredient(ingredient); 
                return Request.CreateResponse(HttpStatusCode.OK, result); 
 
            } 
            catch (RecipeManagerException ex) 
            { 
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message); 
            } 
        } 
 
        //[Authorize(Roles = "Admin, SupportCallIndex")] 
        public HttpResponseMessage UpdateIngredient(Ingredient ingredient) 
        { 
            try 
            { 
                CommandResult<Ingredient> result = dto.UpdateIngredient(ingredient); 
                return Request.CreateResponse(HttpStatusCode.OK, result); 
            } 
            catch (RecipeManagerException ex) 
            { 
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message); 
            } 
        } 
 
        [HttpPost] 
        //[Authorize(Roles = "Admin, SupportCallIndex")] 
        public HttpResponseMessage DeleteIngredient(Ingredient ingredient) 
        { 
            try 
            { 
                CommandResult<Ingredient> result = dto.DeleteIngredient(ingredient); 
                return Request.CreateResponse(HttpStatusCode.OK, result); 
            } 
            catch (RecipeManagerException ex) 
            { 
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message); 
            } 
        } 
 
        public HttpResponseMessage GetAll() 
        { 
            try 
            { 
                CommandResult<Ingredient> result = dto.ReadIngredient(); 
                return Request.CreateResponse((result.Status == CommandStatus.Success ? HttpStatusCode.OK : HttpStatusCode.InternalServerError), result); 
            } 
            catch (RecipeManagerException ex) 
            { 
                return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message); 
            } 
        } 
 
 
    } 
} 

这是我的 WebApiConfig 代码:

using System.Web.Http; 
using Microsoft.Owin.Security.OAuth; 
 
namespace RecipeManager.UI.Htmll5 
{ 
    public static class WebApiConfig 
    { 
        public static void Register(HttpConfiguration config) 
        { 
 
            config.MapHttpAttributeRoutes(); 
 
            config.Routes.MapHttpRoute( 
                name: "DefaultApi", 
                routeTemplate: "api/{controller}/{id}", 
                defaults: new { id = RouteParameter.Optional } 
            ); 
        } 
    } 
} 

这是我的应用骨架的结构:

非常感谢!

请您参考如下方法:

如果你想让你的代码保持原样,那么在默认路由之前添加这条路由:

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

如@Lex 所述,为 id 参数添加了默认值。