asp.net 本地测试Web API时出现404 Not found错误

zyfwsgd6  于 2022-11-26  发布在  .NET
关注(0)|答案(4)|浏览(338)

这是我第一次尝试在一个项目中使用WEB API,我没有任何成功...
我不断得到404错误,当我尝试和达到我的api路线在Fiddler。
我试着在网上看了很多,甚至在这里下面的链接,但有这么多的组合,我不知道什么会工作.
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 }
            );
        }
    }
}

全局.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);
        }
    }
}

我尝试调用的控制器方法。它只是一个不带参数返回空值的伪方法。它的名称是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
nszi6y05

nszi6y051#

URI中不需要FuelTicketImageRetrievalSvc,它应该只与路由匹配的/api/...一起工作,在那里有svc名称会导致它不匹配。

mcvgt66p

mcvgt66p2#

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

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

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

bq3bfh9z

bq3bfh9z3#

为了保证快速运行(有时是首选方法),请在方法之前添加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操作Map到此方法
    1.路由值确保直接Map到URL。作为REST标准,“Get”、“Delete”等不用作URL中的前缀。HTTP操作用于此操作。
    1.有些方法会自动Map到合适的URL,但由于您的类名是“FuelTicketImageRetrievalController”,方法名是“GetSpecificFuelTicket”,因此这并不简单。
    1.返回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”格式可能更好。方法中的任何参数名称都会自动Map到名称相似的查询参数。因此,您的方法看起来如下所示:

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

有关URLMap和路由web-API的详细信息,请参阅链接:

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

iq3niunx4#

当我在Mvc解决方案中添加WebApi支持时,最初出现了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);

它解决了我的问题

相关问题