ASP.NET 4.5 MVC 4 Web APIプロジェクトでは、カスタムHttpMessageHandler
を追加します。次のように私は、(\ App_Satrt \ WebApiConfig.csに)WebApiConfig
クラスを変更しました:Web APIでHttpMessageHandlerを実装する方法は?
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: null,
handler: new MyCustomizedHttpMessageHandler()
);
}
}
は、その後、私はMyCustomizedHttpMessageHandler
を開発:
public class MyCustomizedHttpMessageHandler : HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
IPrincipal principal = new GenericPrincipal(
new GenericIdentity("myuser"), new string[] { "myrole" });
Thread.CurrentPrincipal = principal;
HttpContext.Current.User = principal;
return Task<HttpResponseMessage>.Factory.StartNew(() => request.CreateResponse());
}
}
ただし、APIへのリクエストを(のはhttp://mylocalhost.com/api/valuesを言わせて)データなしで常にステータスコード200を返します。つまり、ValuesController.csの 'GET()'メソッドに到達することはありません。
私は何が欠けていますか? HttpMessageHandler
を正しく実装するにはどうすればよいですか?
PS:私を助けていない、https://stackoverflow.com/a/12030785/538387:すでにこれを読んだことがあります。
ありがとうございます。解決策(1)はうまくいきます。しかし、2番の新しいHttpControllerDispatcher()は次のように言っています:** System.Web.Http.Dispatcher.HttpControllerDispatcherには0引数を取るコンストラクタが含まれていません** - 更新:コードを修正しました。ありがとうございました。 – Tohid
私は上記投稿too.thanksを更新しました。 –
またあなたのanswereにクオンルの回答のこの部分を追加してください:**カスタムメッセージハンドラを作成するには、あなたがから派生する必要があり 'System.Net.Http.DelegatingHandler' ** – Tohid