我正在.Net Core 2.1中创建一个应用程序,我正在使用http客户端进行Web请求.问题是我必须发送并行调用来节省时间,为此我使用的是Task.WhenAll()方法但是当我点击这个方法时,我得到错误"这个实例已经启动了一个或多个请求.属性只能被修改在发送第一个请求之前"以前我使用的是RestSharp,一切都很好,但我想使用httpclient.这是代码:
public async Task<User> AddUser(string email)
{
var url = "user/";
_client.BaseAddress = new Uri("https://myWeb.com/");
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(Constants."application/json"));
_client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
var json = new {email = email }
var response = await _client.PostAsJsonAsync(url,json);
if (response .IsSuccessStatusCode)
{ ....
Run Code Online (Sandbox Code Playgroud)
这是构造函数:
private readonly HttpClient _httpClient;
public UserRepository(HttpClient httpClient)
{
_httpClient = httpClient;
}
Run Code Online (Sandbox Code Playgroud)
方法调用:
var user1 = AddUser("user@user.com");
var user2 = AddUser("test@test.com");
await Task.WhenAll(user1, user2);
Run Code Online (Sandbox Code Playgroud)
这是启动配置:
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
Run Code Online (Sandbox Code Playgroud)
那么我做错了什么?我是否需要使用AddTransient()更改AddSingleton,还是有任何其他问题.还有一个问题我需要在响应之后使用_client.Dispose()因为我所遵循的教程没有使用dispose方法所以我对此感到困惑.
我试图在我的.net核心2.0项目中使用HttpClient,为此我已经在我的控制器中注入了HttpClient.但是,当我尝试在我的startup.cs中配置httpclient时,我收到此错误:"IServiceCollection不包含AddHttpClient的定义".我已经引用了using Microsoft.AspNetCore.Http;
,using Microsoft.Extensions.DependencyInjection;
这就是我要做的事情:
services.AddHttpClient<TestController>();
Run Code Online (Sandbox Code Playgroud)
它在具有相同命名空间的其他项目中工作正常,但在这里我得到了错误.有帮助吗?
我正在尝试使用 .net core 2.1 实现 Aspnet.security.openidconnect (ASOS) 我可以使用 ASOS 成功生成 access_token 和 refreshtoken 但是当我在我的任何操作上添加授权属性并尝试使用邮递员调用该操作时,我得到了以下异常:
InvalidOperationException: No authentication handler is registered for the scheme Bearer. The registered schemes are: ASOS. Did you forget to call AddAuthentication().Add[SomeAuthHandler
Run Code Online (Sandbox Code Playgroud)
这是代码:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddOpenIdConnectServer(options =>
{
options.AuthorizationEndpointPath = "/connect/authorize";
// Enable the token endpoint.
options.TokenEndpointPath = "/connect/token";
// Implement OnValidateTokenRequest to support flows using the token endpoint.
options.Provider.OnValidateTokenRequest = context =>
{
// Reject token requests that don't …
Run Code Online (Sandbox Code Playgroud) asp.net oauth-2.0 openid-connect asp.net-core asp.net-core-2.0
我有一个引导下拉菜单:
<div class="dropdown>
<a class="dropdown-toggle" href="#" id="menu1" data-toggle="dropdown"><img src="@imagePath" class="img-circle dropbtn" alt="Product" style="width:30px;height:30px;" /></a>
<ul class="dropdown-menu" id="productDD" role="menu" aria-labelledby="menu1"></ul>
</div>
Run Code Online (Sandbox Code Playgroud)
现在 ul 通过 ajax 调用在页面加载时加载产品。问题是当我单击下拉菜单中的任何产品时,下拉菜单会关闭。但我只想在 ul 之外的任何地方单击鼠标时关闭下拉菜单
我在div内有多个跨距,但都在同一条线上.我想在新线上写下每一个跨度.这是html代码:
.divContent {
position: absolute;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
width: 100%;
bottom: 5%;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
z-index: 2;
opacity: .8
}
.divContent span {
font-size: 0.875rem;
color: #4D575D;
margin: 0 3px;
}
Run Code Online (Sandbox Code Playgroud)
<div id="content" class="divContent">
<span>Span 1</span>
<span>Span 2</span>
<span>Span 3</span>
</div>
Run Code Online (Sandbox Code Playgroud)
现在这段代码的结果是:Span 1 Span 2 Span 3
但我想要
跨度1
跨度2
跨度3
我的存储库中有一个方法,它调用 datacontext.Add 方法并返回 resutl.Entity,如下所示:
var result = _dataContext.Product.Add(product);
await _dataContext.SaveChangesAsync();
return result.Entity;
Run Code Online (Sandbox Code Playgroud)
现在我想创建模拟,EntityEntry<Product>
但出现异常:
消息:Castle.DynamicProxy.InvalidProxyConstructorArgumentsException:无法实例化类的代理:Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry`1[[Product、Product.Entities、Version=1.0.0.0、Culture=neutral、PublicKeyToken=null]]。找不到无参数构造函数。
这是我的测试方法代码:
var productMock = new Mock<EntityEntry<Product>>();
var entity = new Product{Id = 1, Name = "Bag"};
mappingMock.Setup(m => m.Entity).Returns(entity);
var dataContextMock = new Mock<DataContext>(_options);
var productMockSet = new Mock<DbSet<Product>>();
dataContextMock.Setup(a => a.Product)
.Returns(productMockSet.Object);
dataContextMock.Setup(m => m.Product.Add(It.IsAny<Product>())).Returns(productMock.Object);
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?或者还有其他方法来断言 EntityEntry 吗?
我使用Moq为单元测试创建模拟,但是当我不得不为httpclient的getasync方法创建模拟时,我陷入了困境。以前我使用的是SendAsync方法,为此,我可以使用以下代码:
var mockResponse =
new HttpResponseMessage(HttpStatusCode.OK) {Content = new StringContent(expectedResponse)};
mockResponse.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var mockHandler = new Mock<DelegatingHandler>();
mockHandler
.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.Is<HttpRequestMessage>(
message => message.Headers.Contains("Authorization")
&& message.Headers.Authorization.Parameter.Equals(accessToken)
&& message.Headers.Authorization.Scheme.Equals("Bearer")
&& message.RequestUri.AbsoluteUri.Contains(baseUrl)
),
ItExpr.IsAny<CancellationToken>())
.Returns(Task.FromResult(mockResponse));
Run Code Online (Sandbox Code Playgroud)
现在我有一个方法:
private async Task<List<Model>> GetData()
{
string url = url;
_httpClient.BaseAddress = new Uri(url);
_httpClient.DefaultRequestHeaders.Add(Headers.AuthorizationHeader, "Bearer" + "token");
var response = await _httpClient.GetAsync(url);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsAsync<List<Model>>();
}
Run Code Online (Sandbox Code Playgroud)
现在我可以为此方法创建模拟了吗(getasync)?有什么帮助吗?
我在 .net core 中有一个应用程序,我在其中一项服务中使用 automapper。现在的问题是我正在编写测试方法并模拟自动映射器,但它返回 null。以下是服务方法:
var users = _mapper.Map<IList<User>>(data);
Run Code Online (Sandbox Code Playgroud)
这是使用 Moq 进行的模拟:
var userLogsList = new List<User>() { new User() {Id = "1234", Name= "Dummy User"}};
var mapperMock = new Mock<IMapper>();
mapperMock.Setup(m => m.Map<List<UserEntity>, IList<User>>(It.IsAny<List<UserEntity>>()))
.Returns(userLogsList);
Run Code Online (Sandbox Code Playgroud)
现在这个模拟每次都返回 null。我究竟做错了什么?
我有一个 .net core 3.1 应用程序,我将其作为 docker 容器部署在 aws ecs 上。现在我想在我的 dockerfile 中指定环境变量,我试图在我的代码中使用它,但每次我都没有得到任何价值。
这是.net核心:
private IWebHostEnvironment Environment { get; set; }
public IConfiguration Configuration { get; set; }
public void ConfigureServices(IServiceCollection services)
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{Environment.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Run Code Online (Sandbox Code Playgroud)
现在我想用我在 Dockerfile 中指定的值替换 environment.EnvironmentName 但它不起作用。另外我在某处读到我可以在执行 docker-run 命令时指定环境变量,但在我的情况下我不能这样做,因为 aws ecs 正在运行 docker 容器
这是 docker 文件:
FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build-env
WORKDIR /app
# Copy everything else and build
COPY . ./
ENV ASPNETCORE_ENVIRONMENT Development
RUN …
Run Code Online (Sandbox Code Playgroud) 我有以下字符串:
"Parent1:Child1"
"Parent1:Child2"
"Parent1:Child3"
"Parent1:Child4"
"Parent2:Child1"
"Parent2:Child2"
"Parent2:Child3"
"Parent2:Child4"
"Parent3:Child1"
"Parent3:Child2"
Run Code Online (Sandbox Code Playgroud)
现在我想创建如下字符串:
Parent1:Child1,Child2,Child3,Child4
Parent2:Child1,Child2,Child3,Child4
Parent3:Child1,Child2
Run Code Online (Sandbox Code Playgroud)
我尝试了很多方法,但没有一种方法可以正常工作.有帮助吗?
我在一个字符串里面有X509签名证书,如:
var signingCertificate = -----BEGIN CERTIFICATE-----\r\nMIICTjCCAbegAw.........-----END CERTIFICATE-----
Run Code Online (Sandbox Code Playgroud)
现在我想阅读这个证书的内容.我知道我们可以使用X509Certificate2对象,但直接从文件读取.反正有没有从字符串中读取内容?
asp.net ssl-certificate x509certificate2 x509certificate asp.net-core
asp.net-core ×6
asp.net ×4
c# ×3
httpclient ×3
moq ×3
unit-testing ×3
.net ×2
css ×2
html ×2
xunit ×2
amazon-ecs ×1
aws-ecr ×1
css3 ×1
docker ×1
flexbox ×1
html5 ×1
javascript ×1
jquery ×1
oauth-2.0 ×1