【问题标题】:404 not found error when locally testing web api本地测试 web api 时 404 not found 错误
【发布时间】:2014-06-18 10:41:34
【问题描述】:

这是我第一次尝试在项目中使用 WEB API,但没有成功...

当我尝试在 Fiddler 中访问我的 api 路由时,我不断收到 404 错误。

我尝试在网络上查找很多内容,甚至在下面的链接中查找,但是有太多的组合,我不确定哪种方法会起作用。

HTTP 404 Page Not Found in Web Api hosted in IIS 7.5

如果有人可以帮助我获得正确的设置,我会真的感激不尽。

这是我的代码: Web.config 文件:

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=301879
  -->
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <section name="FuelTicketImageRetrievalSvc.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    </sectionGroup>
  </configSections>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    <add key="AssignedGroup" value="FMS Maintenance Level 3" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5.1" />
    <httpRuntime targetFramework="4.5.1" />
  </system.web>
  <system.webServer>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-5.1.0.0" newVersion="5.1.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
  <system.serviceModel>
    <bindings />
    <client />
  </system.serviceModel>
  <applicationSettings>
    <FuelTicketImageRetrievalSvc.Properties.Settings>
      <setting name="FuelTicketImageRetrievalSvc_IncidentService_HPD_IncidentInterface_Create_WSService" serializeAs="String">
        <value>http://miavsbremweb/arsys/services/ARService?server=miavsbremapp.ryder.com&amp;webService=HPD_IncidentInterface_Create_WS</value>
      </setting>
    </FuelTicketImageRetrievalSvc.Properties.Settings>
  </applicationSettings>
</configuration>

WebApiConfig.cs 文件:

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

namespace FuelTicketImageRetrievalSvc
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

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

Global.asax.cs 文件:

using FuelTicketImageRetrieval;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace FuelTicketImageRetrievalSvc
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            GlobalConfiguration.Configure(WebApiConfig.Register);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}

我试图调用的控制器方法。它只是一个虚拟方法,只返回不带参数的 null。它的名字是 FuelTicketImageRetrievalController:

public string GetSpecificFuelTicket()
        {
            try
            {
                return null;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

我的项目名为FuelTicketImageRetrievalSvc。我已通过项目中的 Web 设置验证正在使用 IIS Express 并设置为

http://localhost:11581/

url 路径调用。

http://localhost:11581/FuelTicketImageRetrievalSvc/api/GetSpecificFuelTicket

【问题讨论】:

    标签: c# asp.net asp.net-mvc asp.net-web-api asp.net-web-api-routing


    【解决方案1】:

    您不需要在 uri 中使用 FuelTicketImageRetrievalSvc,它应该可以与 /api/... 一起使用 这就是您的路线匹配的内容,那里有 svc 名称会导致它不匹配。

    【讨论】:

    • 好的..我现在收到 500 错误...尝试在该方法的断点处实际调试。当 IE 显示“你想从 localhost> 打开或保存 GetSpecificFuelTicket”时,我该如何处理?
    【解决方案2】:

    您需要在路径中添加控制器并删除您的项目

    http://localhost:11581/api/FuelTicketImageRetrieval/GetSpecificFuelTicket
    

    您在引用控制器部分时删除它 - /FuelTicketImageRetrieval/ 来自 FuelTicketImageRetrievalController 而不是项目。 Web API 会在查找正确的类时自动将控制器添加回名称。

    【讨论】:

    • 好的..我现在收到 500 错误...尝试在该方法的断点处实际调试。当 IE 显示“你想从 localhost> 打开或保存 GetSpecificFuelTicket”时,我该如何处理?
    • 用提琴手敲打它,然后点击原始选项卡以查看发送回的确切内容。通常 IE 抱怨它正在获取它不理解的数据。通常是 JSON。但至少现在您访问了您的网站:) 尝试返回一个空字符串而不是 null - 也许它无法消除 null。很难说错误 500 是错误的一般错误。
    • 我现在正在打它。谢谢.. 我有另一种方法称为 GetSpecificFuelTicket(int value)。我这样称呼它“localhost:11581/api/GetSpecificFuelTicketAsync/6460194”,但我得到了 404。这不是带参数调用方法的正确方式吗?
    • 您应该将其作为查询字符串的一部分传递 GetSpecificFuelTicketAsync?value=6460194 您可能需要将 FromUrl 属性添加到方法中,请参阅asp.net/web-api/overview/formats-and-model-binding/…
    【解决方案3】:

    为了快速保证运行(有时是首选方法),请在您的方法之前添加 HTTP 操作前缀和路由属性:

        [HttpGet]
        [Route("api/Products/SpecificFuelTicket")]
        public string GetSpecificFuelTicket()
        {
            try
            {
                return null;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
    

    现在,您可以使用 URL 访问它:

    http://localhost:xxxx/api/products/SpecificFuelTicket
    

    注意事项:

    1. HTTPGet 确保只有 Get 操作映射到此方法
    2. 路由值确保直接映射到 URL。作为 REST 标准,“获取”、“删除”等不用作 URL 中的前缀。 HTTP 操作用于此目的。
    3. 有些方法会自动映射到合适的 URL,但由于您的类名是“FuelTicketImageRetrievalController”,方法名是“GetSpecificFuelTicket”,所以这并不重要。
    4. 返回 null 不是问题。它被序列化为“null”。

    对于您向 Charles 提出的另一个问题,如果您想使用 URL“localhost:xxxx/api/GetSpecificFuelTicketAsync/6460194”,并且您的方法签名采用 int,您可以将路由前缀更改如下(同样,不使用“Get " 在路线中):

        [HttpGet]
        [Route("api/Products/SpecificFuelTicket/{value}")]
        public string GetSpecificFuelTicket(int value)
        {
            try
            {
                return "Your ticket is " + value.ToString();
            }
            catch (Exception ex)
            {
                return null;
            }
        }
    

    但是,正如 Charles 建议的那样,使用“api/Products/SpecificFuelTicket?value=6460194”格式可能会更好。方法中的任何参数名称都会自动映射到类似名称的查询参数。所以,你的方法看起来像:

    [HttpGet]
    [Route("api/Products/SpecificFuelTicket")]
    public string GetSpecificFuelTicket(int value)
    {
       ....
    }
    

    关于URL映射和路由web-API的详细理解,请参考链接:

    1. Attribute Routing in Web API 2
    2. Routing and Action Selection

    【讨论】:

      【解决方案4】:

      当我将 WebApi 支持添加到我的 Mvc 解决方案时,我最初遇到了 404 错误。

      我的 global.asax.cs 包含以下行:

              AreaRegistration.RegisterAllAreas();
              FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
              RouteConfig.RegisterRoutes(RouteTable.Routes);
              BundleConfig.RegisterBundles(BundleTable.Bundles);
              GlobalConfiguration.Configure(WebApiConfig.Register);
      

      我发现当我改变他的WebApiConfig这一行时,代码块变成了:

              AreaRegistration.RegisterAllAreas();
              GlobalConfiguration.Configure(WebApiConfig.Register);
              FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
              RouteConfig.RegisterRoutes(RouteTable.Routes);
              BundleConfig.RegisterBundles(BundleTable.Bundles);
      

      它解决了我的问题

      【讨论】:

        猜你喜欢
        • 2021-01-12
        • 2015-08-11
        • 2019-06-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多