2016-03-26 9 views
1

Web APIを含むASP.NET Webforms Webサイトがあります。このサイトは、WebサーバーとしてIIS Expressを使用してWindows 8上でVisual Studio 2013および.NET 4.5で開発およびテストされています。WebフォームでWeb APIを使用すると404エラーが返される

私は次のように定義されたルートディレクトリ内のWeb APIのコントローラを追加しました:

[RoutePrefix("api")] 
public class ProductsController : ApiController 
{ 
    Product[] products = new Product[] 
    { 
     new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 }, 
     new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M }, 
     new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M } 
    }; 
    [Route("ProductsController")] 
    [HttpGet] 
    public IEnumerable<Product> GetAllProducts() 
    { 
     return products; 
    } 

    public Product GetProductById(int id) 
    { 
     var product = products.FirstOrDefault((p) => p.Id == id); 
     if (product == null) 
     { 
      throw new HttpResponseException(HttpStatusCode.NotFound); 
     } 
     return product; 
    } 

    public IEnumerable<Product> GetProductsByCategory(string category) 
    { 
     return products.Where(
      (p) => string.Equals(p.Category, category, 
       StringComparison.OrdinalIgnoreCase)); 
    } 
} 

Global.asaxのは、次のようになります。私はこれらの2行でが含まれている

public class Global : HttpApplication 
{ 
    void Application_Start(object sender, EventArgs e) 
    { 
     // Code that runs on application startup 
     AreaRegistration.RegisterAllAreas(); 
     RouteConfig.RegisterRoutes(RouteTable.Routes); 


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

    } 
} 

私のweb.configファイル

<validation validateIntegratedModeConfiguration="false"/> 
<modules runAllManagedModulesForAllRequests="true"/> 

次のURLでgetリクエストを行うと、http://localhost:5958/api/products、HTTPエラー404.0が表示されます。私は別の解決策を試みたが、何も働かない。私が紛失しているものがありますか?この問題を解決するにはどうすればよいですか?

ありがとうございます。

答えて

0

コードに基づいて、webapiのルートは含まれていませんでした。 NugetからWebapiをインストールすると、WebApiのルート設定を含むApp_Startの下にWebApiConfigファイルが見つかります。 WEBAPI

using System.Web.Http; 
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.ascxで、この静的メソッドのための新しいルート設定ファイルを作成しない場合。

using System.Web.Http; 
void Application_Start(object sender, EventArgs e) 
    { 

     GlobalConfiguration.Configure(WebApiConfig.Register); 
     // Code that runs on application startup 
     RouteConfig.RegisterRoutes(RouteTable.Routes); 
     BundleConfig.RegisterBundles(BundleTable.Bundles); 
    } 
+0

私はそれをすべてやっていますが、それでも同じ問題です。 web.configで何かを変更する必要がありますか? –

1

ウェブAPIのコンベンショナルベースルーティングと属性ルーティングを混在させています。

Attribute Routing in ASP.NET Web API 2

あなたは、あなたが適切にadd the routesあなたのコントローラに必要なルーティング属性を使用しようとしている場合。

[RoutePrefix("api/products")] 
public class ProductsController : ApiController 
{ 
    //...code removed for brevity 

    //eg: GET /api/products 
    [HttpGet] 
    [Route("")] 
    public IEnumerable<Product> GetAllProducts(){...} 

    //eg: GET /api/products/2 
    [HttpGet] 
    [Route("{id:int}")] 
    public Product GetProductById(int id){...} 

    //eg: GET /api/products/categories/Toys 
    [HttpGet] 
    [Route("categories/{category}")] 
    public IEnumerable<Product> GetProductsByCategory(string category){...} 
} 

あなたのルートが正しく定義されているので、enable attribute routingが必要です。

public class Global : HttpApplication { 
    void Application_Start(object sender, EventArgs e) { 
     //ASP.NET WEB API CONFIG 
     // Pass a delegate to the Configure method. 
     GlobalConfiguration.Configure(WebApiConfig.Register); 

     // Code that runs on application startup 
     AreaRegistration.RegisterAllAreas(); 
     RouteConfig.RegisterRoutes(RouteTable.Routes); 
    } 
} 

WebフォームのRouteConfig

public static class RouteConfig 
{ 
    public static void RegisterRoutes(RouteCollection routes) 
    { 
     var settings = new FriendlyUrlSettings(); 
     settings.AutoRedirectMode = RedirectMode.Permanent; 
     routes.EnableFriendlyUrls(settings); 
    } 
} 

リソース:

WebApiConfig.cs

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

     // Enable attribute routing 
     config.MapHttpAttributeRoutes(); 

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

を次のようにGlobal.asaxのコードを更新してくださいCan you use the attribute-based routing of WebApi 2 with WebForms?

+0

コントローラークラスはどこに追加しますか? –

+0

本当に関係ありません。ほとんどの人は 'Controllers'という名前のフォルダを作成してそこに置きます。プロジェクトにクラスが含まれると、 – Nkosi

+0

は機能しませんでした。すべての属性を追加し、global.asaxファイルを更新しました。 Web APIを有効にした新しいWebフォームプロジェクトを作成しました。 Web APIのコントローラは正常に動作します。私はtisプロジェクトからそのファイルにすべてのファイルをコピーすることを考えています。 –

関連する問題