繁体   English   中英

WebApi端点始终显示“404 not found”

[英]WebApi endpoint always gives “404 not found”

我试图在一个全新的Web应用程序中实现WebApi端点,但无论我尝试什么,我总是在尝试从所述端点进行GET时得到“404 not found”。

找不到localhost / api / dataservice / vehicles

我开始简单,只是试图从数据库中提取车辆列表。

我的应用程序的目录结构如下所示:

目录结构

相关的代码位如下所示:

dataService.js

(function () {

var injectParams = ['vehiclesService'];

var dataService = function (vehiclesService) {
    return vehiclesService;
};

dataService.$inject = injectParams;

angular.module('teleAiDiagnostics').factory('dataService', dataService);
}());

vehiclesService.js

(function () {

var injectParams = ['$http', '$q'];

var vehiclesFactory = function ($http, $q) {
    var serviceBase = '/api/dataservice/',
        factory = {};

    factory.getVehicles = function () {
        return $http.get(serviceBase + 'vehicles').then(function (response) {
            var vehicles = response.data;
            return {
                totalRecords: parseInt(response.headers('X-InlineCount')),
                results: vehicles
            };
        });
    };

    return factory;
};

vehiclesFactory.$inject = injectParams;

angular.module('teleAiDiagnostics').factory('vehiclesService', vehiclesFactory);
}());

DataServiceController.cs

using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;

namespace TeleAiDiagnostics
{
    public class DataServiceController : ApiController
    {
        TeleAiRepository _TeleAiRepository;

        public DataServiceController()
        {
            _TeleAiRepository = new TeleAiRepository();
        }

        [HttpGet]
        public HttpResponseMessage Vehicles()
        {
            List<TeleAiVehicle> vehicles = _TeleAiRepository.GetVehicles();
            HttpContext.Current.Response.Headers.Add("X-inlineCount", vehicles.Count.ToString());
            return Request.CreateResponse(HttpStatusCode.OK, vehicles);
        }
    }
}

vehiclesController.js

(function () {
    var injectParams = ['$location', 'dataService'];

    var VehiclesController = function ($location, dataService) {
        var vm = this;

        vm.vehicles = [];

        function init() {
            dataService.getVehicles()
                .then(function (data) {
                    vm.vehicles = data.results;
                }, function (error) {
                    var thisError = error.data.message;
                });
        };

        init();
    };

    VehiclesController.$inject = injectParams;

    angular.module('teleAiDiagnostics').controller('VehiclesController', VehiclesController);
}());

WebApiConfig.cs

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Linq;
using System.Web.Http;
using System.Web.Routing;

namespace TeleAiDiagnostics
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {

            config.MapHttpAttributeRoutes();

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

            config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

            // Remove default XML handler
            var matches = config.Formatters
                                .Where(f => f.SupportedMediaTypes
                                             .Where(m => m.MediaType.ToString() == "application/xml" ||
                                                         m.MediaType.ToString() == "text/xml")
                                             .Count() > 0)
                                .ToList();

            foreach (var match in matches)
                config.Formatters.Remove(match);
        }
    }
}

的Global.asax.cs

using System;
using System.Web.Http;

namespace TeleAiDiagnostics
{
    public class Global : System.Web.HttpApplication
    {

        protected void Application_Start(object sender, EventArgs e)
        {
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            GlobalConfiguration.Configuration.EnsureInitialized();
        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }
    }
}

RouteConfig.cs

namespace TeleAiDiagnostics
{
    public class RouteConfig
    {
    }
}

我已经尝试过关于我在网上找到的每个教程的说明,但我仍然没有运气。

无论提供什么帮助,我们都非常感谢。

谢谢,

伊恩

我们有答案!

Dan Dumitru和jps都是正确的。 尝试IIS Express后,我意识到了我的错误。

端点确实是http://localhost/TeleAiDiagnostics/api/dataservice/vehicles ,而不仅仅是http://localhost/api/dataservice/vehicles

不知道为什么花了很长时间才意识到这一点。 无论如何,我要感谢大家的帮助。

这可能是因为您的默认Web API路由。 认为它应该是:

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

(没有{action}部分)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM