andrewdavey / postal

Email sending for asp.net mvc using the view engine system to render emails.
http://aboutcode.net/postal
MIT License
536 stars 169 forks source link

System.ArgumentNullException with .NET 4.5.2 WebApi #174

Open youngki924 opened 6 years ago

youngki924 commented 6 years ago

Followed the instruction from http://hangfire.readthedocs.io/en/latest/tutorials/send-email.html

    [HttpPost]
    public IHttpActionResult SendPostal([FromBody] MyMailModel objModelMail)
    {
        if (ModelState.IsValid)
        {
            try
            {
                var email = new NewCommentEmail
                {
                    To = objModelMail.To,
                    UserName = objModelMail.Subject,
                    Comment = objModelMail.Body
                };

                email.Send();

            }
            catch (Exception e)
            {
                return Ok(e);
            }
        }

        return Ok("Email sent");
    }

Got an exception:

{ "ClassName": "System.ArgumentNullException", "Message": "Value cannot be null.", "Data": null, "InnerException": null, "HelpURL": null, "StackTraceString": " at System.Web.HttpBrowserCapabilitiesWrapper..ctor(HttpBrowserCapabilities httpBrowserCapabilities)\r\n at System.Web.HttpRequestWrapper.get_Browser()\r\n at System.Web.WebPages.BrowserHelpers.GetOverriddenBrowser(HttpContextBase httpContext, Func2 createBrowser)\r\n at System.Web.WebPages.DisplayModeProvider.<.ctor>b__2(HttpContextBase context)\r\n at System.Web.WebPages.DefaultDisplayMode.CanHandleContext(HttpContextBase httpContext)\r\n at System.Web.WebPages.DisplayModeProvider.<GetAvailableDisplayModesForContext>d__4.MoveNext()\r\n at System.Web.Mvc.VirtualPathProviderViewEngine.GetPath(ControllerContext controllerContext, String[] locations, String[] areaLocations, String locationsPropertyName, String name, String controllerName, String cacheKeyPrefix, Boolean useCache, String[]& searchedLocations)\r\n at System.Web.Mvc.VirtualPathProviderViewEngine.FindView(ControllerContext controllerContext, String viewName, String masterName, Boolean useCache)\r\n at System.Web.Mvc.ViewEngineCollection.<>c__DisplayClass6.<FindView>b__4(IViewEngine e)\r\n at System.Web.Mvc.ViewEngineCollection.Find(Func2 lookup, Boolean trackSearchedPaths)\r\n at System.Web.Mvc.ViewEngineCollection.FindView(ControllerContext controllerContext, String viewName, String masterName)\r\n at Postal.EmailViewRenderer.CreateView(String viewName, ControllerContext controllerContext)\r\n at Postal.EmailViewRenderer.Render(Email email, String viewName)\r\n at Postal.EmailService.Send(Email email)\r\n at Postal.Email.Send()\r\n at MyTestApp.Controllers.EmailController.SendPostal(MyMailModel objModelMail)", "RemoteStackTraceString": null, "RemoteStackIndex": 0, "ExceptionMethod": "1\n.ctor\nSystem.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\nSystem.Web.HttpBrowserCapabilitiesWrapper\nVoid .ctor(System.Web.HttpBrowserCapabilities)", "HResult": -2147467261, "Source": "System.Web", "WatsonBuckets": null, "ParamName": "httpBrowserCapabilities" }

phantomtypist commented 6 years ago

@youngki924 Can I get a little more info? What type of project and what target framework version?

Thanks.

youngki924 commented 6 years ago

@phantomtypist My current application is deployed to company's app server. So view engines might be different from typical use.

packages.config

package id="Microsoft.AspNet.Mvc" version="5.1.2" targetFramework="net452" package id="Microsoft.AspNet.Razor" version="3.1.2" targetFramework="net452" package id="Microsoft.AspNet.WebApi.Client" version="5.1.1" targetFramework="net45" package id="Microsoft.AspNet.WebApi.Core" version="5.1.1" targetFramework="net45" package id="Microsoft.AspNet.WebPages" version="3.1.2" targetFramework="net452" package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net452" package id="Newtonsoft.Json" version="4.5.11" targetFramework="net45" package id="Postal.Mvc5" version="1.2.0" targetFramework="net452" package id="RazorEngine" version="3.4.1" targetFramework="net452" //company packages package id="XXXX.Toolkit.Interfaces.Shared" version="1.0.0.11" targetFramework="net452" package id="XXXX.AppServer.Interfaces" version="1.5.0.14" targetFramework="net452"

I tried FileSystemRazorViewEngine and it worked but that is not what I can use for actual implementation. https://github.com/andrewdavey/postal/issues/36

Instead of email.Send(), I tried EmailService and customized EmailViewRenderer to set HttpContextWrapper and got the different exception. FindView looks had a problem.

Before var httpContext = new HttpContextWrapper( new HttpContext( new HttpRequest("", UrlRoot(), ""), new HttpResponse(TextWriter.Null) ) ); After HttpRequest request = new HttpRequest("", UrlRoot(), ""); request.Browser = new HttpBrowserCapabilities { Capabilities = new Dictionary<string, string> { {"majorversion", "10"}, {"browser", "IE"}, {"isMobileDevice","false"} } }; // A dummy HttpContextBase that is enough to allow the view to be rendered. var httpContext = new HttpContextWrapper( new HttpContext( request, new HttpResponse(TextWriter.Null) )

Exception { "ClassName": "System.NullReferenceException", "Message": "Object reference not set to an instance of an object.", "Data": null, "InnerException": null, "HelpURL": null, "StackTraceString": " at System.Web.WebPages.FileExistenceCache.<.ctor>b4(String path)\r\n at System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey key, Func2 valueFactory)\r\n at System.Web.WebPages.FileExistenceCache.FileExists(String virtualPath)\r\n at System.Web.Mvc.BuildManagerViewEngine.FileExists(ControllerContext controllerContext, String virtualPath)\r\n at System.Web.Mvc.VirtualPathProviderViewEngine.<>cDisplayClass7.b3(String path)\r\n at System.Web.WebPages.DefaultDisplayMode.GetDisplayInfo(HttpContextBase httpContext, String virtualPath, Func2 virtualPathExists)\r\n at System.Web.WebPages.DisplayModeProvider.GetDisplayInfoForVirtualPath(String virtualPath, HttpContextBase httpContext, Func2 virtualPathExists, IDisplayMode currentDisplayMode, Boolean requireConsistentDisplayMode)\r\n at System.Web.Mvc.VirtualPathProviderViewEngine.GetPathFromGeneralName(ControllerContext controllerContext, List`1 locations, String name, String controllerName, String areaName, String cacheKey, String[]& searchedLocations)\r\n at System.Web.Mvc.VirtualPathProviderViewEngine.GetPath(ControllerContext controllerContext, String[] locations, String[] areaLocations, String locationsPropertyName, String name, String controllerName, String cacheKeyPrefix, Boolean useCache, String[]& searchedLocations)\r\n at System.Web.Mvc.VirtualPathProviderViewEngine.FindView(ControllerContext controllerContext, String viewName, String masterName, Boolean useCache)\r\n at System.Web.Mvc.ViewEngineCollection.<>cDisplayClass6.b5(IViewEngine e)\r\n at System.Web.Mvc.ViewEngineCollection.Find(Func`2 lookup, Boolean trackSearchedPaths)\r\n at System.Web.Mvc.ViewEngineCollection.FindView(ControllerContext controllerContext, String viewName, String masterName)\r\n at XXX.MyTestApp.Controllers.CustomEmailViewRenderer.CreateView(String viewName, ControllerContext controllerContext)\r\n at XXX.MyTestApp.Controllers.CustomEmailViewRenderer.Render(Email email, String viewName)\r\n at Postal.EmailService.Send(Email email)\r\n at XXX.MyTestApp.Controllers.TestController.SendPostal(MyMailModel objModelMail)", "RemoteStackTraceString": null, "RemoteStackIndex": 0, "ExceptionMethod": "8\n<.ctor>b4\nSystem.Web.WebPages, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\nSystem.Web.WebPages.FileExistenceCache\nBoolean <.ctor>b__4(System.String)", "HResult": -2147467261, "Source": "System.Web.WebPages", "WatsonBuckets": null }

Thanks

phantomtypist commented 6 years ago

Dumb question, but I want to cover the bases.... this exception occurs on both your machine and the actual server the application is deployed to OR does the exception only occur on the server?

phantomtypist commented 6 years ago

I'll just throw this out there too. In the folder that I keep the views I had to create a web.config with the following content:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.web.webPages.razor>
    <pages>
      <namespaces>
        <add namespace="Postal" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>
</configuration>

This was in an MVC 5 project targeting .NET Framework 4.5.

phantomtypist commented 6 years ago

And another "double-checking" question: Did you try to scaffold a completely blank MVC 5 project with Postal and your Razor view and try to send the email? You know, just for sanity sake?

I'm somewhat wondering if there is a dependency/reference issue.

phantomtypist commented 6 years ago

With regards to the NuGet packages you have installed... is there anything prohibiting you from upgrading to the newer/latest minor and patch versions of the following packages?:

youngki924 commented 6 years ago

@phantomtypist Even on my local, I need to install company's app server locally and deploy my application there.

I am developing Web api and got an error after configuration change to App.conf. (I don't have web.conf)

pageBaseType was added because it was required:

<pages pageBaseType="System.Web.Mvc.WebViewPage">

Error: Could not process request: http://localhostxxxx. Exception has been thrown by the target of an invocation.

I did not try pure MVC5 yet.

Thanks.

austindenz412 commented 1 year ago

It seems like you encountered an exception related to the HttpBrowserCapabilitiesWrapper in the provided code. This might be caused by the context in which you're trying to create the email object. The stack trace suggests an issue with the HttpContextBase and HttpBrowserCapabilities. Double-check that you're using the correct context and that all Postal Codes required dependencies are properly set up. It's also beneficial to ensure compatibility with the version of .NET and libraries you are using. Debugging step by step and verifying the inputs could help pinpoint the exact cause of this exception.

ronaust816 commented 11 months ago

Encountering a System.ArgumentNullException in .NET 4.5.2 en vivo WebApp. Any guidance on resolving this issue would be greatly appreciated!