2016-04-11 4 views
1

Надеюсь, вы, ребята, можете мне помочь.Контроллер AngularJS не находит контроллер C#

У меня есть простой проект, все еще находящийся в зачаточном состоянии, но не могу получить контроллер AngularJS (componententAdmin.controller), чтобы найти мой контроллер C# API.

Я получаю сообщение об ошибке: 404/Not Найдено: Запрос URL: http://localhost:31021/api/ingredientAdmin/PostIngredient/

Мой AngularJS контроллер и контроллер C# в различных проектах, и я ссылаться мой C# контроллер проекта в моем проекте AngularJS.

Я также пробовал различные варианты написания и т. Д., Но думаю, что я могу что-то упустить.

Вот мой контроллер AngularJS: 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 контроллер #: 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 код:

Это структура моего приложения скелета:

App Layout

Спасибо очень!

+3

Вам нужно POST для '/ API/ingredientAdmin', а не'/API/ingredientAdmin/PostIngredient/' – haim770

+3

Или добавить новый маршрут:' апи/{контроллер}/{действие}/{идентификатор} ' – Ric

ответ

2

Если вы хотите сохранить ваш код, как это в настоящее время, а затем добавить этот маршрут до дефолта:

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

как было упомянуто @lex, добавлено по умолчанию для id паров.

+0

Thank вы за совет. Я уверен, что это моя проблема (одна из них), но я просто не могу заставить ее работать. По-прежнему получается такая же ошибка. Я изменил routeTemplate, чтобы включить {action}. Есть ли что-нибудь еще, что я могу пропустить? При отладке он переходит прямо из моего запроса $ http.post к моей ошибке. – onmyway

+0

Вы пытались отладить контроллер api, чтобы проверить его? – Ric

+0

@onmyway Вам, вероятно, придется пометить '{id}' как необязательный, используя свойство 'defaults'. – Lex

1

WebApi/HttpPost имеет несколько странных оговорок об этом.

Смотрите мой ответ (не вопрос, но мой ответ) здесь:

Web api not supporting POST method

Обратите внимание на метод на Апи контроллера:

[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/

и th является статья

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

+0

Спасибо за ваши отзывы. К сожалению, все еще застрял на этом. – onmyway

1

Вы можете добавить RoutePrefix и Route в контроллер:

[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) { 

         }); 

надеюсь, это поможет.

+0

Спасибо за помощь. Мне нравится ваш метод. К сожалению, я все еще получаю 404: http: // localhost: 31021/api/componententAdmin/PostIngredient/не найден. Я решил копать немного глубже, и я занят некоторыми учебниками на WebApi спереди назад. Я вернусь, когда решит проблему. – onmyway

+0

попробуйте localhost: 3021/api/PostIngredient адрес, без «ingridientAdmin», надеюсь, что это поможет, если нет - сообщите мне. –

Смежные вопросы