3

WebAPI を使用します。

作成したテストの 1 つは、特定のコントローラーに対して、許可されている場合にのみ GET 動詞を使用できるようにすることでした。

MVC HelpPages を使用するテストが作成されました

HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(baseAddress);
config.Routes.MapHttpRoute(
    "SearchAPI", 
    "api/{controller}/{id}");

HttpSelfHostServer server = new HttpSelfHostServer(config);
server.OpenAsync().Wait();
IApiExplorer apiExplorer = config.Services.GetApiExplorer();
var apiDescriptions = apiExplorer.ApiDescriptions;
var data = from description in apiDescriptions
           where description.ActionDescriptor.ControllerDescriptor.ControllerType.FullName.StartsWith("MySite.Presentation.Pages.SearchAPI")
           orderby description.RelativePath
           select description
           ;
foreach (var apiDescription in data)
{
    Assert.That(apiDescription.HttpMethod, Is.EqualTo(HttpMethod.Get), string.Format("Method not Allowed: {0} {1}", apiDescription.RelativePath, apiDescription.HttpMethod));
}

このテストは、コントローラーが適切な場合に GET HTTP VERB メソッドのみを使用することを保証する最良の方法ではなかったかもしれませんが、機能しました。

MVC5 にアップグレードしたので、このテストは失敗しました。HttpSelfHostServer が利用できなくなったため

Microsoft の msdn ライブラリを見ると、HttpSelfHostServer の使用は推奨されていませんが、代わりに Owin の使用が推奨されています。

新しい Owin クラスから始めました

public class OwinStartUp
{
    public void Configuration(IAppBuilder appBuilder)
    {
        var config = new HttpConfiguration();
        config.Routes.MapHttpRoute(
            name: "SearchAPI",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        AreaRegistration.RegisterAllAreas();
        appBuilder.UseWebApi(config); 
    }
}

しかし、テストに関しては、これは私が得ることができた限りです

        string baseAddress = "http://localhost/bar";
        using (var server = WebApp.Start<OwinStartUp>(url: baseAddress))
        {


        }

Intellisenseによって提案されているサーバー変数にパブリックメソッドがないため、構成からサービスにアクセスしてGetApiExplorerメソッドを呼び出す方法がわかりません..

Owin の使用方法を示すいくつかのサイトを見てきましたが、この問題の解決には役立ちませんでした: http://www.asp.net/web-api/overview/hosting-aspnet-web-api/use- owin-to-self-host-web-api

この既存の質問もあり ます。Owin を使用すると、ASP.NET Web API 2 ヘルプ ページが機能し ませんが、問題の解決には役立ちませんでした。

特定の HTTP 動詞のみがコントローラー/メソッドに対して許可されていることを確認するための単体テストを作成できるようにするために、または API ヘルプページを使用するように Owin を構成する方法について、何をする必要がありますか?

4

2 に答える 2

4

このシナリオでは、サーバーを起動する必要はありません。たとえば、次のようにして API の説明を取得できます。API の説明を取得するために、API Explorer は実際のリクエストを実行して API の説明を取得する必要がないことに注意してください。

var config = new HttpConfiguration();

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

IApiExplorer explorer = config.Services.GetApiExplorer();

var apiDescs = explorer.ApiDescriptions;
于 2014-02-04T00:59:18.600 に答える