3

asp.net MVC アプリケーションからメールを送信する必要があり、MVC メーラーを使用して仕事をしています。HTTPContext がある限り、正常に機能します。残念ながら、コンテキストのないメールも送信する必要があります。

MVC Mailer の新しいバージョンには CurrentHttpContext の仮想プロパティがあり、それを「偽の」コンテキストで設定すると、ローカルで動作するように見えます。サーバーに到達するとすぐに機能しなくなり、次のスタック トレースで失敗します。

System.ArgumentNullException: Value cannot be null.
Parameter name: httpContext
  at System.Web.HttpContextWrapper..ctor(HttpContext httpContext)
  at Glimpse.Core.Extensibility.GlimpseTimer.get_TimerMetadata()
  at Glimpse.Mvc3.Plumbing.GlimpseViewEngine.FindView(ControllerContext controllerContext, String viewName, String masterName, Boolean useCache)
  at System.Web.Mvc.ViewEngineCollection.<>c__DisplayClassc.<FindView>b__a(IViewEngine e)
  at System.Web.Mvc.ViewEngineCollection.Find(Func`2 lookup, Boolean trackSearchedPaths)
  at System.Web.Mvc.ViewEngineCollection.Find(Func`2 cacheLocator, Func`2 locator)
  at Mvc.Mailer.MailerBase.ViewExists(String viewName, String masterName)
  at Mvc.Mailer.MailerBase.PopulateBody(MailMessage mailMessage, String viewName, String masterName, Dictionary`2 linkedResources)
  at Mvc.Mailer.MailerBase.Populate(Action`1 action)

私はいくつかの調査を行いましたが、HTTPContext で探しているものが原因で ViewEngineCollection が見つからないという問題があるようです。私が返す「偽の」コンテキストは次のように単純です

  public static HttpContextBase GetHttpContext(string baseUrl)
  {
      if (HttpContext.Current == null)
     {
    Log.InfoFormat("Creating a fake HTTPContext using URL: {0}", baseUrl);
    var request = new HttpRequest("/", baseUrl, "");
    var response = new HttpResponse(new StringWriter());
    return new HttpContextWrapper(new HttpContext(request, response));
      }

   return new HttpContextWrapper(HttpContext.Current);
  }

「偽の」コンテキストから何かが欠けていますか? どうすれば追加できますか?

4

1 に答える 1

0

HttpContextBase とリクエスト/レスポンスをモックまたは偽造する必要があります。

RhinoMocks を使用している場合は、次のように実行できます。

var httpResponse = MockRepository.GenerateMock<HttpResponseBase>();
var httpRequest = MockRepository.GenerateMock<HttpRequestBase>();
// you may need to stub specific methods of request/response
var context = MockRepository.GenerateMock<HttpContextBase>();
            context.Stub(r => r.Request).Return(httpRequest);
            context.Stub(r => r.Response).Return(httpResponse);

または、基本クラスから継承する場合は偽造できます。質問でラッパーに渡す HttpContext は機能しません。

于 2012-12-05T12:45:40.267 に答える