AngularJS控制器未找到C#控制器

时间:2016-04-11 14:50:18

标签: c# angularjs asp.net-web-api

我希望你们能帮助我。

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

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

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

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

这是我的AngularJS控制器:ingredientAdminController:

animation-fill-mode

这是我的C#控制器: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;
            }

        }


    };


}
)();

这是我的WebApiConfig代码:

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);
            }
        }


    }
}

这是我的应用程序框架的结构:

App Layout

非常感谢!

3 个答案:

答案 0 :(得分:2)

如果您想保留当前的代码,请在默认值之前添加此路由:

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

如@Lex所述,添加了id param的默认值。

答案 1 :(得分:1)

WebApi / HttpPost有一些奇怪的警告。

在这里看到我的答案(不是问题,但我的答案):

Web api not supporting POST method

注意Api控制器上的方法:

  [System.Web.Http.HttpPost]
    public MyOutputObject DoSomething([FromBody]MyInputObject args)
    {
        Console.Writeline(args.ToString());
    }

请注意这篇文章:

http://www.dontpaniclabs.com/blog/post/2013/01/23/That-Pesky-Requested-Resource-Does-Not-Support-HTTP-Method-POST-Error-When-Using-MVC-Web-API/

和本文

http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/

答案 2 :(得分:1)

您可以将 RoutePrefix 路线添加到您的控制器中:

[RoutePrefix("api")]

    public class IngredientAdminController : ApiController
        {
            private RecipeManager.DTO.IngredientAdminDTO dto = new IngredientAdminDTO();

        [Route("PostIngredient")]
        [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);
            }
        }

您的要求:

var req = {
method: 'POST',
url: '/api/PostIngredient',
data: data
};

$http(req).then(function successCallback(responseSuccess) {

                        }, function errorCallback(responseError) {

                        });
希望它有所帮助。