小编Cha*_*glu的帖子

无法解析类型为'System.Net.Http.HttpClient'的服务

我创建了一个ViewComponent类,REST API使用调用了HttpClient,这是代码:

public class ProductsViewComponent : ViewComponent
{
    private readonly HttpClient _client;

    public ProductsViewComponent(HttpClient client)
    {
        _client = client ?? throw new ArgumentNullException(nameof(client));
    }

    public async Task<IViewComponentResult> InvokeAsync(string date)
    {
        using(var response = await _client.GetAsync($"/product/get_products/{date}"))
        {
            response.EnsureSuccessStatusCode();
            var products = await response.Content.ReadAsAsync<List<Products>>();
            return View(products);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

InvalidOperationException:尝试激活MyApp.ViewComponents.ProductsViewComponent时无法解析类型为'System.Net.Http.HttpClient'的服务

我注射HttpClientConfigureService方法提供Startup了这种方式:

 services.AddHttpClient<FixturesViewComponent>(options =>
 {
    options.BaseAddress = new Uri("http://80.350.485.118/api/v2");
 });
Run Code Online (Sandbox Code Playgroud)

更新:

我也注册了ProductsViewComponent同样的错误。

c# asp.net asp.net-core

9
推荐指数
3
解决办法
8324
查看次数

SupportedUICultures 不显示所有文化

我按照这个文档在我的ASP.NET Core应用程序中实现本地化,我试图在页脚中显示一个包含我的应用程序支持的所有语言的选择。

所以我_SelectLanguagepartial按照文档的建议创建了一个文件:

@using Microsoft.AspNetCore.Builder
@using Microsoft.AspNetCore.Http.Features
@using Microsoft.AspNetCore.Localization
@using Microsoft.AspNetCore.Mvc.Localization
@using Microsoft.Extensions.Options

@inject IViewLocalizer Localizer
@inject IOptions<RequestLocalizationOptions> LocOptions

@{
    var requestCulture = Context.Features.Get<IRequestCultureFeature>();
    var cultureItems = LocOptions.Value.SupportedUICultures
        .Select(c => new SelectListItem { Value = c.Name, Text = c.DisplayName })
        .ToList();
    var returnUrl = string.IsNullOrEmpty(Context.Request.Path) ? "~/" : $"~{Context.Request.Path.Value}";
}

<div title="@Localizer["Request culture provider:"] @requestCulture?.Provider?.GetType().Name">
    <form id="selectLanguage" asp-controller="Language"
          asp-action="SetLanguage" asp-route-returnUrl="@returnUrl"
          method="post" class="form-horizontal" role="form">
        <label asp-for="@requestCulture.RequestCulture.UICulture.Name">@Localizer["Language:"]</label>
        <select name="culture" onchange="this.form.submit();"
                asp-for="@requestCulture.RequestCulture.UICulture.Name"
                asp-items="cultureItems"></select>
    </form>
</div>
Run Code Online (Sandbox Code Playgroud)

我通过以下方式将其加载到页脚中:

@await …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-mvc asp.net-core

5
推荐指数
1
解决办法
1394
查看次数

无法创建异步Main

我正在尝试制作Main异步,所以我尝试了:

class Program
{
    static async Task Main(string[] args)
    {
        Books books = new Books();
        await books.AddBooksAsync();
    }
}
Run Code Online (Sandbox Code Playgroud)

AddBooksAsync这个结构在哪里:

public async Task AddBooksAsync()
{
  //some contents
}
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

不包含适用于入口点的静态"主"方法

c#

2
推荐指数
1
解决办法
1566
查看次数

如何获得下个月的日子?

我想要实现的目标

我想要获得两个月(当前)和下个月的天数.实际上我使用该代码成功实现了这一点:

int monthDays = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);
string[] days = Enumerable.Range(1, monthDays).Select(x => x.ToString("D2")).ToArray();
Run Code Online (Sandbox Code Playgroud)

基本上我使用了该函数DaysInMonth,然后我生成了一个List<int>代表那个月的日子.

问题

现在,我想要了解下个月的日子,但我有一些问题需要处理以下情况:

December 2018 (current)
January 2019 (next)
Run Code Online (Sandbox Code Playgroud)

我尝试了什么

正如你所看到的那样year已经改变了,所以我为下一个月的日子编写的代码将会失败:

var nextMonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(1);
monthDays = DateTime.DaysInMonth(DateTime.Now.Year, nextMonth.Month);
days = Enumerable.Range(1, monthDays).Select(x => x.ToString("D2")).ToArray();
Run Code Online (Sandbox Code Playgroud)

我怎样才能管理next本月的新年?

c# datetime daycount

2
推荐指数
1
解决办法
106
查看次数

无法订购特定的ID

我正在尝试为特定role_id订单订购结果,因此:

$query = "SELECT p.*
FROM player_career cr
LEFT JOIN player p ON p.id = cr.player_id
WHERE team_id = :team_id AND season_id = :season_id
ORDER BY p.role_id (1, 2, 3, 4)";
Run Code Online (Sandbox Code Playgroud)

我明白了:

Syntax error or access violation: 1305 FUNCTION p.role_id does not exist
Run Code Online (Sandbox Code Playgroud)

这是什么错误?

mysql sql

1
推荐指数
1
解决办法
31
查看次数

包含内容的元素的XPath?

我正在使用HtmlAgilityPack,我有以下情况:

<table class='table-main odds '>   
   <tbody>
      <tr>..</tr>
      <tr>..</tr>
      <tr>..</tr>
      <tr></tr>
      <tr></tr>
  </tbody>
</table>          
Run Code Online (Sandbox Code Playgroud)

你可以看到tr里面只有三个内容,所以我希望在最终结果中应该只有前三个tr.实际上我的代码返回所有tr:

 HtmlNode oddsTable = doc.DocumentNode
          .SelectSingleNode("//table[starts-with(@class, 'table-main')]");
 HtmlNodeCollection rows = oddsTable.SelectNodes("tbody//tr");
Run Code Online (Sandbox Code Playgroud)

我怎样才能实现这个目标xpath

感谢您的帮助和解释.

html c# xml xpath html-agility-pack

1
推荐指数
1
解决办法
45
查看次数

无法使用SendGrid

我正在尝试使用SendGrid我的ASP.NET Core应用程序发送电子邮件,所以我按以下方式配置它:

ConfigureServices方法内部,我添加了一个Singleton和配置来访问SendGridAPI:

services.AddSingleton<IEmailSender, IEmailSender>();
services.Configure<AuthMessageSenderOptions>(Configuration);
Run Code Online (Sandbox Code Playgroud)

该类AuthMessageSenderOptions是软件配置的一部分:

public class AuthMessageSenderOptions
{
    public string SendGridUser { get; set; }
    public string SendGridKey { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

此类管理SendGrid用户名和密钥.

我创建了一个service实现IEmailSender接口的类,这是实现:

public class EmailSender : IEmailSender
{
    public AuthMessageSenderOptions Options { get; }

    public EmailSender(IOptions<AuthMessageSenderOptions> optionsAccessor)
    {
        Options = optionsAccessor.Value;
    }

    public Task SendEmailAsync(string email, string subject, string message)
    {
        return Execute(Options.SendGridKey, subject, message, email); …
Run Code Online (Sandbox Code Playgroud)

c# asp.net sendgrid asp.net-core

1
推荐指数
1
解决办法
128
查看次数

如何在缓存中存储数据?

我创建了一个ViewComponent来显示 a List<Product>,该列表是从REST API服务中获取的数据进行评估的,这是我的类实现:

public class ProductsViewComponent : ViewComponent
{
    private readonly HttpClient _client;

    public ProductsViewComponent(HttpClient client)
    {
        _client = client ?? throw new ArgumentNullException(nameof(client));
    }

    public async Task<IViewComponentResult> InvokeAsync(string date)
    {
       using (var response = await _client.GetAsync($"/"product/get_products/{date}"))
       {
           response.EnsureSuccessStatusCode();
           var products = await response.Content.ReadAsAsync<List<Product>>();
           return View(products);
       }
    }
}
Run Code Online (Sandbox Code Playgroud)

我将列表加载到Components文件夹中可用的 html 表中:Views\Shared\Components\Products\Default.cshtml

在每个View需要显示Products我所做的:

@await Component.InvokeAsync("Products", new { date = myDate })
Run Code Online (Sandbox Code Playgroud)

使用以下配置REST API进行调用:HttpClient …

c# asp.net asp.net-core-mvc asp.net-core

1
推荐指数
1
解决办法
1万
查看次数

转换中丢失的小数点

我有一个包含:2.53的字符串,我正在尝试将此数字转换为decimal类型,所以我做了:

string value = "2.53";
decimal converted = Convert.ToDecimal(value);
Run Code Online (Sandbox Code Playgroud)

但最终的结果是: 253

c#

0
推荐指数
1
解决办法
38
查看次数