Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Martin Rud 231 posts 901 karma points c-trib
    Apr 15, 2022 @ 14:01
    Martin Rud
    0

    How to read settings from appsettings.json in a view?

    Hi forum,

    I have Googled and tried (with only errors), so now I ask here. :)

    In a view I want to read some values from appsettings.json. I have found some code that seems to be part of the solution:

    MrAppsettings.cs:

    using Microsoft.Extensions.Options;
    using Umbraco.Cms.Core.Configuration.Models;
    
    namespace MrAppsettings
    {
        public class SomeClass
        {
            private GlobalSettings _globalSettings;
    
            public SomeClass(IOptions<GlobalSettings> globalSettings)
            {
                _globalSettings = globalSettings.Value;
    
                var smtpHost = _globalSettings.Smtp.Host;
            }
        }
    }
    

    1) As I can read this must be registered in Startup.cs, but how?

    2) And how do I "call" the class in my cshtml views?

  • Guido Adam 21 posts 65 karma points
    Apr 15, 2022 @ 14:09
    Guido Adam
    101

    What you're doing here is DI. This is (a small) part of the solution.

    Example:

    Your appsettings.json:

    "EmailSettings": {
      "MailServer": "",
      "MailPort": ,
      "Email": "",
      "Password": "",
      "SenderName": "",
      "Sender": "",
      "SysAdminEmail": ""
    },
    

    Register the service (so you can do DI) in startup.cs:

    services.Configure<EmailSettings>(configuration.GetSection("EmailSettings"));
    

    Settings Class:

    public class EmailSettings
    {
      public string MailServer { get; set; }
      public int MailPort { get; set; }
      public string SenderName { get; set; }
      public string Sender { get; set; }
      public string Email { get; set; }
      public string Password { get; set; }
      public string SysAdminEmail { get; set; }
    }
    

    Class, constructor and usage:

    private readonly IOptions<EmailSettings> _emailSettings;
    
    public EmailSender(IOptions<EmailSettings> emailSettings)
    {
      _emailSettings = emailSettings;
    }
    
    email.From.Add(new MailboxAddress(_emailSettings.Value.SenderName, _emailSetting.Value.Sender));
    
Please Sign in or register to post replies

Write your reply to:

Draft