Angular MVC ajax调用404未找到

时间:2016-11-27 05:59:21

标签: angularjs ajax asp.net-mvc asp.net-mvc-4

我是角色的新手,并尝试调用从角度到新创建的mvc webapi控制器执行crud操作...无法绕过现在获得的404。寻求专业人士的一些指导,谢谢!

角:

angular.module('PersonApp').service('PersonService', ['$http', function` ($http) {

    var PersonService = {};
    var urlBase = '/api/PersonApi/';

    PersonService.getPersons = function () {
        console.log(urlBase);
        return $http.get(urlBase);
    };

    PersonService.upsertPerson = function (person) {
        return $http.post(urlBase, person); //must have ,person !!!!!!!!!!
    };

    PersonService.removePerson = function (id) {
        return $http.delete(urlBase + id);
    };

    return PersonService;

}]);

PersonApi.cs api:

public class PersonApi : ApiController
{
    TutorialDataEntities ef_Db = new TutorialDataEntities();
    Repository.Repository PersonRepository = new Repository.Repository();

    [Route("api/PersonApi/{person}")]
    [HttpPost]
    public HttpResponseMessage UpsertPerson([FromBody]DTOPerson person)
    {
        if (ModelState.IsValid) // and if you have any other checks
        {
            var result = PersonRepository.UpsertPerson(person);
            formatDate(result.birthDate);
            return Request.CreateResponse(HttpStatusCode.Created, result);
        }
        return Request.CreateResponse(HttpStatusCode.BadRequest);
    }

    [Route("api/PersonApi/{id}")]
    [HttpDelete]
    public HttpResponseMessage RemovePerson([FromUri]int id)
    {
        PersonRepository.RemovePerson(id);
        return Request.CreateResponse(HttpStatusCode.OK);
    }

    [Route("api/PersonApi/")]
    [HttpGet]
    public HttpResponseMessage GetPersons()
    {
        var result = PersonRepository.GetAllPersons();
        foreach (var person in result)
        {
            formatDate(person.birthDate);
        }

        if (result == null)
            return Request.CreateResponse(HttpStatusCode.NotFound);

        return Request.CreateResponse(HttpStatusCode.OK, result);

    }

    private DateTime formatDate(DateTime date)
    {
        return Convert.ToDateTime(date.ToString("MM/dd/yyyy"));
    }
}

我的解决方案资源管理器:

enter image description here

WebApiConfig.cs

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

Routeconfig.cs

public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }

0 个答案:

没有答案