小编Ser*_*rge的帖子

为什么 HttpClient 即使在 Startup 中设置了基地址也不保留基地址

在我的 .net core Web api 项目中,我想使用外部 API,以便获得预期的响应。

我注册和使用 HttpClient 的方式如下。在启动中,我添加了以下代码,称为命名类型 httpclient 方式。

 services.AddHttpClient<IRecipeService, RecipeService>(c => {
                c.BaseAddress = new Uri("https://sooome-api-endpoint.com");
                c.DefaultRequestHeaders.Add("x-raay-key", "123567890754545645gggg");
                c.DefaultRequestHeaders.Add("x-raay-host", "sooome-api-endpoint.com");
            });
Run Code Online (Sandbox Code Playgroud)

除此之外,我还有 1 个服务,我在其中注入了 HttpClient。


    public class RecipeService : IRecipeService
    {
        private readonly HttpClient _httpClient;

        public RecipeService(HttpClient httpClient)
        {
           _httpClient = httpClient;
        }

        public async Task<List<Core.Dtos.Recipes>> GetReBasedOnIngAsync(string endpoint)
        {
            
            using (var response = await _httpClient.GetAsync(recipeEndpoint))
            {
                // ...
            }
        }
    }

Run Code Online (Sandbox Code Playgroud)

创建 httpClient 时,如果我将鼠标悬停在对象本身上,则基本 URI/标头会丢失,并且我不明白为什么会发生这种情况。如果有人能透露一些信息,我将不胜感激:)

第一次更新

该服务正在如下所示的控制器之一中使用。该服务由 DI 注入,然后将相对路径解析为该服务(我假设我已经将基本 URL 存储在客户端中)也许我做错了?


namespace ABC.Controllers
{
    [ApiController]
    [Route("[controller]")] …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-web-api dotnet-httpclient asp.net-core-webapi httpclientfactory

14
推荐指数
3
解决办法
2万
查看次数

是什么导致 JsonException: JSON 值无法转换?

C# 10 / .NET 6 / System.Text.Json

我正在使用一个以 JSON 响应形式返回的 API。我正在尝试System.Text.Json将 JSON 响应反序列化为一个类。我收到 JsonException 并可以帮助理解我做错了什么。

我调用 API 并存储 JSON 响应: string json = await Retreive.Fetch(target);

这是输出Console.WriteLine(json)

[{"id": 1148082,"name": "TestGroup","group_type":"console_group","provisioning_guid": null,"member_count": 1,"current_risk_score": 36.3,"status": "active"},{"id": 1148788,"name": "Group2","group_type": "smart_group","provisioning_guid": null,"member_count": 9,"current_risk_score": 39.7,"status": "active"},{"id": 1148792,"name": "Group3","group_type": "smart_group","provisioning_guid": null,"member_count": 9,"current_risk_score": 39.7,"status": "active"}]
Run Code Online (Sandbox Code Playgroud)

如果有帮助的话,这是一个漂亮的印刷版本:

[
  {
    "id": 1148082,
    "name": "TestGroup",
    "group_type": "console_group",
    "provisioning_guid": null,
    "member_count": 1,
    "current_risk_score": 36.3,
    "status": "active"
  },
  {
    "id": 1148788,
    "name": "Group2",
    "group_type": "smart_group",
    "provisioning_guid": null,
    "member_count": 9, …
Run Code Online (Sandbox Code Playgroud)

.net c# json system.text.json

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

在“包含”操作中无效,因为它不代表属性访问:“t =&gt; t.MyProperty”

我在 Entity Framework Core MVC 应用程序上收到以下错误。任何人都可以帮忙解释为什么吗?我在下面提供了我的模型的简化版本。

InvalidOperationException:表达式“b.BrandId”在“Include”操作中无效,因为它不表示属性访问:“t => t.MyProperty”。要定位在派生类型上声明的导航,请使用强制转换 ('t => ((Derived)t).MyProperty') 或 'as' 运算符 ('t => (t as Derived).MyProperty')。可以通过组合Where、OrderBy(降序)、ThenBy(降序)、Skip 或 Take 操作来过滤集合导航访问。

我有一个产品表和一个品牌表。品牌是唯一的,产品只能有一个品牌,但一个品牌可以有很多产品。

产品型号及品牌型号:

public class Product
{
    public int Id { get; set; } 
    public string Name { get; set; } 
    public int BrandId { get; set; } 
    
    public virtual Brand Brand { get; set; }

    public Product()
    {
        Brand = new Brand();
    }
}

public class Brand
{
    public int BrandId { get; set; }
    
    public string …
Run Code Online (Sandbox Code Playgroud)

c# entity-framework entity-framework-core .net-core

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

JSON.net(反)序列化非类型化属性

假设我有一个这样的类:

public class Example {
    public int TypedProperty { get; set; }
    public object UntypedProperty { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

假设有人出现并写道:

var example = new Example
{
    TypedProperty = 5,
    UntypedProperty = Guid.NewGuid()
}
Run Code Online (Sandbox Code Playgroud)

如果我用 序列化它JsonConvert.SerializeObject(example),我得到

{
  "TypedProperty": 5,
  "UntypedProperty": "24bd733f-2ade-4374-9db6-3c9f3d97b12c"
}
Run Code Online (Sandbox Code Playgroud)

理想情况下,我想得到这样的东西:

{
  "TypedProperty": 5,
  "UntypedProperty":
    {
      "$type": "System.Guid,mscorlib",
      "$value": "24bd733f-2ade-4374-9db6-3c9f3d97b12c"
    }
 }
Run Code Online (Sandbox Code Playgroud)

TypeNameHandling在这种情况下不起作用。如何(反)序列化非类型化属性?

.net c# json json.net

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

在 ASP.Net Core 中检查令牌过期的高性能方法

目前,对于 ASP.NET Core MVC 应用程序的每次调用,我都会在OnValidatePrincipalcookie 的情况下执行以下操作:

  1. id_token通过调用 来获取cookie GetTokenValue
  2. 调用JwtSecurityTokenHandler的 ValidateToken 将 token 转为 json。
  3. ValidTo从 json 中获取属性。
  4. 比较它以查看令牌是否过期。

对我来说,每次通话都这样做似乎有点过分了。我想知道是否有什么办法可以将 ValidTo 值存储在 cookie 本身中。这样我就不必解析 json 来检查每次调用是否过期。

有没有办法让我存储id_token' ValidTo,这样像这样的调用就可以给我过期时间: GetTokenValue("id_token_valid_to")

c# .net-core asp.net-core asp.net-core-3.1

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

重定向到页面 OnActionExecuting 方法 ASP.NET Core 5 MVC

我有一个问题,请求重定向了太多次,我只想转到新的重定向路由,那么如何防止这种情况发生,或者有什么我不知道的事情?

public class AuthController : Controller
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);

        if (GoToLogin)
        {
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary
            {
                { "controller", "account" },
                { "action", "login" }
            });
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

在 EF 上下文中使用 appsettings.json 配置

我应该指出我是 .NET 的新手......

我有以下 appsettings.json 文件:

{
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft": "Warning",
            "Microsoft.Hosting.Lifetime": "Information"
        }
    },
    "ConnectionStrings": {
        "MyContext": "Host=localhost;Database=test;Username=user;Password=''"
    }
}
Run Code Online (Sandbox Code Playgroud)

在 MyContext.cs 文件中,我想从 appsettings.json 配置读取连接字符串:

using Microsoft.EntityFrameworkCore;
using System;
using System.Configuration;

namespace My.Models
{
  public partial class MyContext : DbContext
  {

  protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
  {
    Console.WriteLine(ConfigurationManager.ConnectionStrings.Count);
    if (!optionsBuilder.IsConfigured)
    {
  optionsBuilder.UseNpgsql(ConfigurationManager.ConnectionStrings["MyContext"].ConnectionString);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

ConfigurationManager.ConnectionStrings["MyContext"].ConnectionString为空,有什么想法吗?

我在 Startup.cs via 中成功使用了配置文件Configuration.GetConnectionString("MyContext"),但在这里我想从该配置中读取 ASP.NET 应用程序之外的情况的连接字符串(即在我想要执行的 EF 迁移中using var db = new MyContext();),但我不知道为什么上面返回 …

c# asp.net entity-framework-core .net-core

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

如何使用jquery刷新视图组件而不刷新页面

我的视图中有一个视图组件

 @await Component.InvokeAsync("UserProfileCard")
Run Code Online (Sandbox Code Playgroud)

我希望当我单击按钮时,仅刷新此组件,而无需使用 jquery ajax 或 jquery Unobtrusive 刷新页面

c# asp.net jquery .net-core asp.net-core

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

如何在 cshtml 视图中使用 Asp .NET Core MVC 中的变量?

我正在从 .Net Framework 迁移到 .Net 5.0,并且我尝试在 Razor 视图中使用变量,就像普通的 asp MVC 一样,变量中存在语法@page错误

错误:“@page”指令必须位于 Razor 文件中定义的所有其他元素之前。

错误:“page”指令必须出现在行的开头。

错误:“页面”指令值必须用空格分隔。

代码:

@for (var page = Model.Pager.StartPage; page <= Model.Pager.EndPage; page++)
 {
       if (page == Model.Pager.CurrentPage)
       {
         <li class="active"><span style="line-height:20px">@page</span> </li>
       }
       else
       {
        <li><a href="@Url.Action("Index","Blogs",new { page = @page,pageSize=10 })">@page</a></li>
       }
  }
Run Code Online (Sandbox Code Playgroud)

c# razor .net-core asp.net-core .net-5

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

从带有空格的 JSON 字符串反序列化枚举

我将用这样的事实作为序言:我试图避免使用Newtonsoft.Json,因为表面上看,System.Text.Json它已经准备好在 .NET 6 中迎来黄金时段。

因此,我有两个来自 API 的枚举,我想使用此测试方法对它们进行反序列化:

[Theory]
[ClassData(typeof(TestDataGenerator))]
public void CanDeserialiseEnumsWithCustomJsonStrings(Enum expected, string jsonName)
{
    jsonName.ShouldNotBeNullOrEmpty();
    ReadOnlySpan<char> json = $"{{\"TestEnum\":\"{jsonName}\"}}";

    Type constructed = typeof(TestEnumWrapper<>).MakeGenericType(expected.GetType());
        
    var res = JsonSerializer.Deserialize(json, constructed);

    constructed.GetProperty("TestEnum").GetValue(res).ShouldBe(expected);
}

private class TestEnumWrapper<T> where T: struct
{
    public T TestEnum { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

(是的,我知道这可以通过 来完成JsonSerializer.Deserialize<T>(),我希望能够通过此测试测试许多类型,所以我需要反射 AFAICT)。

第一个,工作正常:

[JsonConverter(typeof(JsonStringEnumConverter))]
public enum RecordType
{
        [JsonPropertyName("country")]
        Country = 1,

        [JsonPropertyName("destinationOrbit")]
        DestinationOrbit = 2,

        [JsonPropertyName("engine")]
        Engine = 3,
        //etc...

}
Run Code Online (Sandbox Code Playgroud)

第二个,反序列化失败,这似乎是由于名称中的空格造成的。

[JsonConverter(typeof(JsonStringEnumConverter))]
public enum …
Run Code Online (Sandbox Code Playgroud)

c# enums json deserialization system.text.json

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