启动执行完成后如何运行控制器?

时间:2019-07-18 14:00:40

标签: asp.net-core model-view-controller .net-core asp.net-core-mvc asp.net-core-2.1

在.net核心应用程序上,我有一个控制器,该控制器从API端点获取令牌并将其保存在缓存中。现在,该控制器需要在UseMvc()中的UseSpa()之后和Startup.Configure之前运行。我可以像这样运行控制器,还是有更好的方法来做到这一点?

我对.net core并不陌生,任何提示或链接都将有所帮助。

需要运行的控制器:

[Route("api/[controller]")]
    [ApiController]
    public class TokensHelperController : AppBaseController
    {
        public TokensHelperController(IConfiguration configuration, IMemoryCache memoryCache, IHttpClientFactory clientFactory) : base(configuration, memoryCache, clientFactory)
        {

        }

        public static async Task<Token> GetToken(Uri authenticationUrl, Dictionary<string, string> authenticationCredentials)
        {
            HttpClient client = new HttpClient();
            FormUrlEncodedContent content = new FormUrlEncodedContent(authenticationCredentials);
            HttpResponseMessage response = await client.PostAsync(authenticationUrl, content);

            if (response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                string message = String.Format("POST failed. Received HTTP {0}", response.StatusCode);
                throw new ApplicationException(message);
            }

            string responseString = await response.Content.ReadAsStringAsync();
            Token token = JsonConvert.DeserializeObject<Token>(responseString);

            return token;
        }

        public IActionResult GetAccessToken()
        {
            Dictionary<string, string> authenticationCredentials_sb = Configuration.GetSection("EX1:Credentials").GetChildren().Select(x => new KeyValuePair<string, string>(x.Key, x.Value)).ToDictionary(x => x.Key, x => x.Value);
            Token token_sb = GetToken(new Uri(Configuration["EX1:URL"]), authenticationCredentials_sb).Result;

            _cache.Set("sb", token_sb.AccessToken);

            return Ok();
        }

    }

1 个答案:

答案 0 :(得分:1)

您可以从控制器中提取缓存逻辑,并将其放入服务和c的接口中。

public interface ITokenService{
    void GetAccessToken();
    Task<Token> GetToken(Uri authenticationUrl, Dictionary<string, string> authenticationCredentials)
}


public class TokenService : ITokenService
{
    public TokenService(IConfiguration configuration, IMemoryCache memoryCache, IHttpClientFactory clientFactory) : base(configuration, memoryCache, clientFactory)
    {
    //set the injected values here like configuration etc.
    }

    public void GetAccessToken()
    {
        Dictionary<string, string> authenticationCredentials_sb = Configuration.GetSection("EX1:Credentials").GetChildren().Select(x => new KeyValuePair<string, string>(x.Key, x.Value)).ToDictionary(x => x.Key, x => x.Value);
        Token token_sb = GetToken(new Uri(Configuration["EX1:URL"]), authenticationCredentials_sb).Result;
        _cache.Set("sb", token_sb.AccessToken);
    }

    public async Task<Token> GetToken(Uri authenticationUrl, Dictionary<string, string> authenticationCredentials)
    {
        HttpClient client = new HttpClient();
        FormUrlEncodedContent content = new FormUrlEncodedContent(authenticationCredentials);
        HttpResponseMessage response = await client.PostAsync(authenticationUrl, content);

        if (response.StatusCode != System.Net.HttpStatusCode.OK)
        {
            string message = String.Format("POST failed. Received HTTP {0}", response.StatusCode);
            throw new ApplicationException(message);
        }

        string responseString = await response.Content.ReadAsStringAsync();
        Token token = JsonConvert.DeserializeObject<Token>(responseString);

        return token;
    }
}

public class TokenService : ITokenService
{
GetAccessToken()
        {
            Dictionary<string, string> authenticationCredentials_sb = Configuration.GetSection("EX1:Credentials").GetChildren().Select(x => new KeyValuePair<string, string>(x.Key, x.Value)).ToDictionary(x => x.Key, x => x.Value);
            Token token_sb = GetToken(new Uri(Configuration["EX1:URL"]), authenticationCredentials_sb).Result;

            _cache.Set("sb", token_sb.AccessToken);
}

现在,如果要通过控制器公开此逻辑,则需要注入ITokenService并使用服务方法。并且您可以在启动时或所需的任何地方使用相同的服务。并且不要忘记在启动配置中注册TokenService。我希望你明白这一点。如果您遇到任何困难,请在下面留下评论。