简体   繁体   English

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

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

I am trying to implement WebApi endpoints in a brand new web app but no matter what I try I always get "404 not found" when trying to do a GET from said endpoint. 我试图在一个全新的Web应用程序中实现WebApi端点,但无论我尝试什么,我总是在尝试从所述端点进行GET时得到“404 not found”。

找不到localhost / api / dataservice / vehicles

I'm starting simple and just trying to pull a list of vehicles from the database. 我开始简单,只是试图从数据库中提取车辆列表。

The directory structure of my application looks like so: 我的应用程序的目录结构如下所示:

目录结构

The relevant bits of code look like so: 相关的代码位如下所示:

dataService.js dataService.js

(function () {

var injectParams = ['vehiclesService'];

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

dataService.$inject = injectParams;

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

vehiclesService.js 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 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 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 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 的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 RouteConfig.cs

namespace TeleAiDiagnostics
{
    public class RouteConfig
    {
    }
}

I've tried the instructions from about every tutorial I could find online and I'm still not having any luck. 我已经尝试过关于我在网上找到的每个教程的说明,但我仍然没有运气。

Whatever help can be provided is greatly appreciated. 无论提供什么帮助,我们都非常感谢。

Thanks, 谢谢,

Ian 伊恩

We have an answer! 我们有答案!

Dan Dumitru and jps were both correct. Dan Dumitru和jps都是正确的。 After trying IIS Express I realized my error. 尝试IIS Express后,我意识到了我的错误。

The endpoint is indeed http://localhost/TeleAiDiagnostics/api/dataservice/vehicles and not simply http://localhost/api/dataservice/vehicles . 端点确实是http://localhost/TeleAiDiagnostics/api/dataservice/vehicles ,而不仅仅是http://localhost/api/dataservice/vehicles

Not sure why it took this long for me to realize this. 不知道为什么花了很长时间才意识到这一点。 Regardless, I want to thank everyone for their help. 无论如何,我要感谢大家的帮助。

It might be because of your default Web API route. 这可能是因为您的默认Web API路由。 I think it should be: 认为它应该是:

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

(without the {action} part) (没有{action}部分)

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

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