小编Nko*_*osi的帖子

如何解决请求与 .Net Core Web Api 中的多个端点匹配的问题

我注意到有很多关于这个主题的类似问题。

调用以下任何方法时出现此错误。

Microsoft.AspNetCore.Routing.Matching.AmbiguousMatchException:请求匹配多个终结点。

但是,我无法弄清楚解决问题的最佳做法是什么。到目前为止,我还没有设置任何特定的路由中间件。

// api/menus/{menuId}/menuitems
[HttpGet("{menuId}/menuitems")]
public IActionResult GetAllMenuItemsByMenuId(int menuId)
{            
    ....
}

// api/menus/{menuId}/menuitems?userId={userId}
[HttpGet("{menuId}/menuitems")]
public IActionResult GetMenuItemsByMenuAndUser(int menuId, int userId)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

c# .net-core asp.net-core-webapi asp.net-core-routing

37
推荐指数
3
解决办法
6万
查看次数

Windows 10更新后,System.DirectoryServices.AccountManagement.PrincipalContext中断

在过去的几年里,我一直在使用这个小功能,没有任何问题来验证用户凭据.该createPrincipalContext方法返回PrincipalContextwith ContextType.Machine和机器名称.

public static bool ValidateCredentials(string username, string password, string domain = null) {
    try {
        using (var principalContext = createPrincipalContext(username, domain)) {
            username = GetLoginInfo(username).Username;
            // validate the credentials
            if (principalContext.ValidateCredentials(username, password)) {
                //once valid check if account is enabled
                using (UserPrincipal user = UserPrincipal.FindByIdentity(principalContext, username)) {
                    return user.Enabled.GetValueOrDefault(false);
                }
            }
        }
    } catch (PrincipalOperationException e) {
        traceError(e);
    } catch (Exception e) {
        traceError(e);
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

我的开发机器最近自动更新到最新版本的Windows 10,从那时起,principalContext.ValidateCredentials一直抛出以下异常.

System.IO.FileNotFoundException:系统找不到指定的文件.

除了机器更新,没有其他更改.我花了最近几天在网上搜索可能导致问题的原因. …

c# filenotfoundexception principalcontext

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

如何测试asp.net核心内置的Ilogger

我想验证记录的一些日志.我使用的是asp.net核心内置的ILogger,并使用asp.net内核的DI注入它:

private readonly ILogger<InvoiceApi> _logger;

public InvoiceApi(ILogger<InvoiceApi> logger)
{
    _logger = logger;
}
Run Code Online (Sandbox Code Playgroud)

然后我用它像: _logger.LogError("error));

我像往常一样通过以下方式嘲笑它(使用moq):

MockLogger = new Mock<ILogger<InvoiceApi>>();
Run Code Online (Sandbox Code Playgroud)

并将其注入服务中以供测试:

new InvoiceApi(MockLogger.Object);
Run Code Online (Sandbox Code Playgroud)

然后尝试验证:

MockLogger.Verify(m => m.LogError(It.Is<string>(s => s.Contains("CreateInvoiceFailed"))));
Run Code Online (Sandbox Code Playgroud)

但它抛出:

对非虚拟(在VB中可覆盖)成员的验证无效:m => m.LogError

那么,如何验证记录的日志?

c# logging unit-testing moq asp.net-core

32
推荐指数
3
解决办法
7139
查看次数

依赖注入,注入参数

我正在使用DI的vNext实现.如何将参数传递给构造函数?例如,我有课:

public class RedisCacheProvider : ICacheProvider
{
    private readonly string _connectionString;

    public RedisCacheProvider(string connectionString)
    {
        _connectionString = connectionString;
    }
    //interface methods implementation...
}
Run Code Online (Sandbox Code Playgroud)

和服务注册:

services.AddSingleton<ICacheProvider, RedisCacheProvider>();
Run Code Online (Sandbox Code Playgroud)

如何将参数传递给RedisCacheProvider类的构造函数?例如Autofac:

builder.RegisterType<RedisCacheProvider>()
       .As<ICacheProvider>()
       .WithParameter("connectionString", "myPrettyLocalhost:6379");
Run Code Online (Sandbox Code Playgroud)

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

31
推荐指数
4
解决办法
3万
查看次数

FromBody字符串参数给出null

这可能是非常基本的东西,但我无法弄清楚我哪里出错了.

我试图从POST的主体中获取一个字符串,但"jsonString"只显示为null.我也想避免使用模型,但也许这是不可能的.我用PostMan打的那段代码是这个块:

[Route("Edit/Test")]
[HttpPost]
public void Test(int id, [FromBody] string jsonString)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

也许这是我对邮递员做错的事情,但我一直试图在身体的价值部分使用"= test"(如在关于这个主题的其他问题中看到的那样) - x-www-form-urlencoded section with密钥作为jsonString而没有.我也尝试过使用raw-text和raw-text/plain.我得到了身份证,所以我知道网址是正确的.任何有关这方面的帮助将不胜感激.

PostMan目前设置如下:

POST http://localhost:8000/Edit/Test?id=111
key = id  value = 111
Body - x-www-form-urlencoded
key = jsonString  value = "=test"
Run Code Online (Sandbox Code Playgroud)

c# asp.net-web-api asp.net-web-api-routing asp.net-web-api2 postman

30
推荐指数
9
解决办法
8万
查看次数

带有IIS的ASP.NET核心 - 不允许HTTP动词

我们有一个ASP.NET Core 2.0网站,它还提供了一些用于UI增强目的的简单Web API方法.

IIS Express下本地运行时,Web API调用按预期工作,但是当我们部署到IIS 8.5生产Web服务器时,在发出HTTP 和请求时会出现以下错误...DELETEPUT

405 Method Not Allowed
Run Code Online (Sandbox Code Playgroud)

经过一些网络搜索后,我们发现了几篇建议删除IIS WebDAV模块的帖子.我们在IIS中禁用了它(它是我们的服务器),我们也尝试了以下方法:

  • 禁用WebDAV
  • 启用WebDev并设置Allow verb filtering = False
  • 处理程序映射,允许所有动词请求限制的设置:aspNetCore,WebDAVExtensionlessUrlHandler-Integrated-4.0

上述步骤都没有解决我们的问题.

任何建议/方向将不胜感激.

asp.net iis asp.net-core asp.net-core-webapi

30
推荐指数
8
解决办法
2万
查看次数

如何在ASP.Net Core中为Server.MapPath获取绝对路径

如何获得ASP网络核心替代方式的绝对路径 Server.MapPath

我试过使用IHostingEnvironment但它没有给出正确的结果.

IHostingEnvironment env = new HostingEnvironment();
var str1 = env.ContentRootPath; // Null
var str2 = env.WebRootPath; // Null, both doesn't give any result 
Run Code Online (Sandbox Code Playgroud)

我在wwwroot文件夹中有一个图像文件(Sample.PNG)我需要获取这个绝对路径.

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

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

ObjectResult和JsonResult有什么区别

Microsoft.AspNetCore.Mvc命名空间中有两个类:

ObjectResultJsonResult.

两者都以JSON格式转换返回的对象.

它们之间有什么区别,使用它们的目的是什么?

json asp.net-core-mvc .net-core asp.net-core

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

assertAll与JUnit5中的多个断言

是否有任何理由对多个断言进行分组:

public void shouldTellIfPrime(){
    Assertions.assertAll(
            () -> assertTrue(isPrime(2)),
            () -> assertFalse(isPrime(4))
    );
}
Run Code Online (Sandbox Code Playgroud)

而不是这样做:

public void shouldTellIfPrime(){
    Assertions.assertTrue(isPrime(2));
    Assertions.assertFalse(isPrime(4));
}
Run Code Online (Sandbox Code Playgroud)

java junit unit-testing assertions junit5

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

如何模拟 IConfiguration.GetValue

我试图模拟顶级(不是任何部分的一部分)配置值(.NET Core 的 IConfiguration),但徒劳无功。例如,这些都不起作用(使用 NSubstitute,但它与 Moq 或我相信的任何模拟包相同):

var config = Substitute.For<IConfiguration>();
config.GetValue<string>(Arg.Any<string>()).Returns("TopLevelValue");
config.GetValue<string>("TopLevelKey").Should().Be("TopLevelValue"); // nope
// non generic overload
config.GetValue(typeof(string), Arg.Any<string>()).Returns("TopLevelValue");
config.GetValue(typeof(string), "TopLevelKey").Should().Be("TopLevelValue"); // nope
Run Code Online (Sandbox Code Playgroud)

就我而言,我还需要GetSection从同一个配置实例调用。

c# nsubstitute .net-core

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