简体   繁体   English

本地测试 web api 时出现 404 not found 错误

[英]404 not found error when locally testing web api

This is my first time trying to use the WEB API in a project and am not having any success with it...这是我第一次尝试在项目中使用 WEB API,但没有成功......

I keep getting 404 errors when I try and reach my api route in Fiddler.当我尝试在 Fiddler 中访问我的 api 路由时,我不断收到 404 错误。

I tried looking a lot on the web and even here at the following link, but there are so many combinations, that I'm not sure what would work.我尝试在网络上查看很多内容,甚至在以下链接中查看了很多内容,但组合太多了,我不确定哪种方法可行。

HTTP 404 Page Not Found in Web Api hosted in IIS 7.5 在 IIS 7.5 中托管的 Web Api 中找不到 HTTP 404 页面

If somebody can please help me with this to get the right settings I would really appreciate it.如果有人可以我这个得到正确的设置,我真的很感激它。

Here is my code: Web.config file:这是我的代码: 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 file: 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 file: 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);
        }
    }
}

Controller method that I'm trying to call.我试图调用的控制器方法。 It's just a dummy method that simply returns null with no parameters.它只是一个无参数返回 null 的虚拟方法。 It's name is FuelTicketImageRetrievalController:它的名字是 FuelTicketImageRetrievalController:

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

The name of my project is called FuelTicketImageRetrievalSvc .我的项目名为FuelTicketImageRetrievalSvc I have verified through the web settings in the project that IIS Express is being used and is set to我已经通过项目中的 web 设置验证了正在使用 IIS Express 并设置为

http://localhost:11581/

url path call. url 路径调用。

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

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

You need to add your controller in the path and remove your project您需要在路径中添加您的控制器并删除您的项目

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

You remove the Controller part when referencing it - the /FuelTicketImageRetrieval/ is from the FuelTicketImageRetrievalController not the project.引用它时删除控制器部分 - /FuelTicketImageRetrieval/ 来自 FuelTicketImageRetrievalController 而不是项目。 Web API will auto add the controller back on the name when looking for the correct class.在寻找正确的类时,Web API 将自动将控制器添加回名称。

For a quick guaranteed run (and sometimes preferred approach), add HTTP action prefix and route attributes before your method:为了快速保证运行(有时是首选方法),请在您的方法之前添加 HTTP 操作前缀和路由属性:

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

Now, you can access it using URL:现在,您可以使用 URL 访问它:

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

Points to note:注意事项:

  1. HTTPGet ensures that only Get action is mapped to this method HTTPGet 确保只有 Get 操作映射到此方法
  2. Route value ensures a direct mapping to a URL.路由值确保直接映射到 URL。 As REST standard, "Get", "Delete" etc.. are not used as prefix in URL.作为 REST 标准,“获取”、“删除”等不用作 URL 中的前缀。 The HTTP action is used for that. HTTP 操作用于此目的。
  3. Some methods are automatically mapped to suitable URLs, but since your class name is "FuelTicketImageRetrievalController" and method name is "GetSpecificFuelTicket", it is not trivial.某些方法会自动映射到合适的 URL,但由于您的类名是“FuelTicketImageRetrievalController”,方法名是“GetSpecificFuelTicket”,因此这并非微不足道。
  4. Returning null is not an issue.返回 null 不是问题。 it is returned serialized as "null".它被序列化为“null”返回。

For your another question to Charles, if you want to use URL "localhost:xxxx/api/GetSpecificFuelTicketAsync/6460194", and your method signature takes int, you can change the route prefix as following (again, not using "Get" in the route):对于您向 Charles 提出的另一个问题,如果您想使用 URL“localhost:xxxx/api/GetSpecificFuelTicketAsync/6460194”,并且您的方法签名采用 int,您可以按如下方式更改路由前缀(同样,不要在路线):

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

However, as Charles suggested, using " api/Products/SpecificFuelTicket?value=6460194 " format is perhaps better.然而,正如查尔斯所建议的,使用“ api/Products/SpecificFuelTicket?value=6460194 ”格式可能更好。 Any parameter name in the method is automatically mapped to similar name query parameter.方法中的任何参数名称都会自动映射到类似名称的查询参数。 So, your method'd look like:所以,你的方法看起来像:

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

For, a detailed understanding of URL mapping and routing web-API, refer to link:对于 URL 映射和路由 web-API 的详细理解,请参考链接:

  1. Attribute Routing in Web API 2 Web API 2 中的属性路由
  2. Routing and Action Selection 路由和动作选择

I originally had a 404 error when I added WebApi support to my Mvc solution.当我将 WebApi 支持添加到我的 Mvc 解决方案时,我最初遇到了 404 错误。

My global.asax.cs contained the lines:我的 global.asax.cs 包含以下几行:

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

What I found is that when I changed he WebApiConfig line, so that the code block became:我发现当我改变他的 WebApiConfig 行时,代码块变成了:

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

it fixed my problem它解决了我的问题

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

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