标签: asp.net-web-api

entity.ToListAsync().Where 或 entity.Where()?

我很难决定哪种方式最适合在我的 WebAPI 2 后端查询我的 SQL Server

我试图尽可能多地使用 async/await,但我发现当我返回整个集合时,没有可用的 async 选项。

哪种方式最好?

[ResponseType(typeof(List<ExposedPublisher>))]
[HttpGet]
public async Task<IHttpActionResult> GetPublisher()
{
    var list = new List<PublisherWithMedia>();
    foreach (var publisher in _db.Publisher.Where(e => e.IsDeleted == false))
    {
        var pub = new PublisherWithMedia()
            {
                Id = publisher.Id,
                Name = publisher.Name,
                Mediae = new List<WebClient.Models.Media>()
            };
            foreach (var media in publisher.Media)
            {
                pub.Mediae.Add(ApiUtils.GetMedia(media));
            }
        list.Add(pub);
    }
    return Ok(list);
}
Run Code Online (Sandbox Code Playgroud)

或者

[ResponseType(typeof(List<PublisherWithMedia>))]
[HttpGet]
public async Task<IHttpActionResult> GetPublisher()
{
    var list = new List<PublisherWithMedia>();
    var entity = await …
Run Code Online (Sandbox Code Playgroud)

c# async-await asp.net-web-api entity-framework-6

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

ASP.NET Core Web API - 使用 InstancePerRequest() 时 Autofac 和 EF Core 的问题

我正在尝试使用AutofacEF CoreAutoMapper设置我的ASP.NET Core Web API项目。

目前,我可以通过以下两种设置使我的项目工作:

  • 将所有内容注册为单例 => SingleInstance() (EF 上下文的并发问题,因为它不是线程安全的)
  • 注册所有内容,以便每次Resolve()调用时都会获得一个新实例=> InstancePerDependency() (额外开销)

不幸的是,我无法使其与InstancePerRequest()范围一起使用。

出于某种原因,我收到以下错误消息:

在此处输入图片说明

这听起来有点像我会InstancePerRequest()singelton服务的某个地方注入这些依赖项......

一旦我将所有内容更改为SingleInstance()InstancePerDependency()一切正常。与InstancePerRequest().

启动文件

    /// <summary>
    /// Is called by the ASP.NET Core application for all environments.
    /// </summary>
    /// <param name="builder">Builder container.</param>
    private static void ConfigureContainer(ContainerBuilder builder, ApplicationName applicationName)
    {
        // For all environments and for only user service specific registrations
        if …
Run Code Online (Sandbox Code Playgroud)

.net entity-framework dependency-injection autofac asp.net-web-api

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

无法使用 Angular 6 读取未定义的属性“名称”

屏幕上显示的值是正确的,但我在日志中收到此错误:ERROR TypeError: Cannot read property 'name' of undefined

我用 '?' 尝试了几种方法 像这样: [(ngModel)]="customer?.name"但不起作用,那么我需要帮助:)

在服务中:

  getCustomer(name:string){
    let url = `http://localhost:8081/api/customer/${name}`;

    return this.http.get<Customer>(url);
  }
Run Code Online (Sandbox Code Playgroud)

在组件的 .ts 中:

customer: Customer;

this.customerService.getCustomer(this.pName)
      .subscribe(
        (data) =>{  
          this.customer = data['customer'];
        },
        err =>{
          console.log('getCustomer failed');
        }
    );
Run Code Online (Sandbox Code Playgroud)

在模板中:

<input type="text" class="form-control" id="myname" required [(ngModel)]="customer.name" name="myname">
Run Code Online (Sandbox Code Playgroud)

但这不行。

你有想法吗 ?

谢谢,

asp.net-web-api typescript angular angular5 angular6

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

以异步方式调用同步方法?

我正在开发一个 ASP.NET MVC WebApi 项目,其中一种方法需要进行 LDAP 搜索。搜索从 LDAP 服务器检索的信息量确保调用至少需要 7 秒才能完成。调用,因为它使用System.DirectoryServices.Protocols类和方法,是同步和不可修改的。

此 API 将接收的流量相当大(即使 API 位于内部网络中),因此每次调用 LDAP 服务器 7 秒并不是一个好主意。所以我想知道这个:

  • 将它包装在异步方法中是个好主意吗?
  • 异步此调用的正确方法是什么?(是await Task.Run(() => Search(params))一种可以接受的方式吗?)

c# ldap-query async-await asp.net-web-api

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

httpclient.GetAsync:底层连接已关闭:发送时发生意外错误

我有一个简单的 web api,它获取一个 url,并生成一个短数字作为短 url。我创建了一个 VS 控制台应用程序,我在其中通过HTTPClient对象调用 web api 。当我第一次运行代码时,它抛出以下错误:

错误消息: 发生了一个或多个错误。

内部异常: System.Net.Http.HttpRequestException:发送请求时出错。---> System.Net.WebException: 基础连接已关闭:发送时发生意外错误。---> System.IO.IOException: 无法从传输连接读取数据:远程主机强行关闭了现有连接。---> System.Net.Sockets.SocketException: 远程主机在 System.Net.Sockets.Sockets.Socket.EndReceive(IAsyncResult asyncResult) 处的 System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult) 处强行关闭了现有连接--- 内部异常堆栈跟踪结束 --- 在 System.Net.TlsStream.EndWrite(IAsyncResult asyncResult) 在 System.Net.ConnectStream.WriteHeadersCallback(IAsyncResult ar) --- 内部异常堆栈跟踪结束 --- 在 System .Net.HttpWebRequest。

这是我用来调用 web api 的代码。通过浏览器调用 web api 工作得很好。

static void Main(string[] args)
{
    string url = "https://app1/api/AddUrl?longUrl=http://google.com";
    var result = GetTinyUrl(url).Result;
    Console.WriteLine(result.ShortUrl);     
}

protected static async Task<UrlResponse> GetUrl(string baseUrl)
{
    HttpClientHandler handler = new HttpClientHandler();
    handler.UseDefaultCredentials = true;

    var …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-web-api

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

从 NSwag swagger 中过滤模式

我有一个带有 API 端点的 ASP.NET 完整框架应用程序。我正在使用 NSwag 生成一个 swagger 文档。这一切都有效。

我只需要为一小部分端点生成一个文档。路径已过滤,但架构未过滤。如何过滤架构对象以匹配路径过滤?

示例:我有这个过滤器

    public class IncludeControllersInSwagger : IOperationProcessor
    {
        public Task<bool> ProcessAsync(OperationProcessorContext context)
        {
            return Task.FromResult(
                context.ControllerType == typeof(ControllerA));
        }
    }
Run Code Online (Sandbox Code Playgroud)

这在启动时:
settings.GeneratorSettings.OperationProcessors.Add(new IncludeControllersInSwagger());

控制器是:

    public class AResponse
    {
        public string Message { get; set; }
        public bool Flag { get; set; }
    }

    public class BResponse
    {
        public string Message { get; set; }
        public int Count { get; set; }
    }

    [Route("a")]
    public class ControllerA : ApiController
    {
        [HttpGet]
        public …
Run Code Online (Sandbox Code Playgroud)

asp.net-web-api swagger nswag

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

Entity Framework Core,一对多关系,集合始终为空

我正在尝试在运行时通过 http 请求建立的 InMemory 数据库中建立一个简单的一对多关系。我是 Entity Framework Core 的新手,所以我不确定这是否是使用它的正确方法。

值控制器.cs

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    private readonly DataListContext _Context;
    public ValuesController(DataListContext context)
    {
        _Context = context;
    }

    [HttpGet]
    public ActionResult<IEnumerable<DataList>> Get()
    { 
        // Datas keeps is value
        Console.WriteLine("Root Count: " + _Context.RootDatas.Count());
        if (_Context.RootDataLists.Count() > 0)
        {
            // InsideDatas is always 
            Console.WriteLine("Inside Count: " + _Context.RootDataLists.First().InsideDatas.Count);empty next request
        }

        return _Context.RootDataLists.ToList();
    }

    [HttpPost]
    public void Post([FromBody] string value)
    {
        var data = new Data() { Id = …
Run Code Online (Sandbox Code Playgroud)

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

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

为什么我不能使用 nlog 将跟踪记录写入文件?

我开始学习如何在 .net core web API 应用程序中配置 nlog。并阅读了一些教程,并尝试从github的官方教程中实现实现

1)创建nlog.confiqxml文件

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  autoReload="true" 
  internalLogLevel="Trace" 
  internalLogFile="D:/Projects/appstore2/AppStore/AppStore.DataAccessLayer/Logs/InnerLog.txt">

<extensions>
  <!--enable NLog.Web for ASP.NET Core-->
  <add assembly="NLog.Web.AspNetCore"/>
</extensions>

<variable name="PathToFile" value="D:/Projects/appstore2/AppStore/AppStore.DataAccessLayer/Logs"/>

<!-- define various log targets -->
<targets async="true">    
  <!-- write logs to file -->
  <target name="logfile" xsi:type="File" fileName="D:/Projects/appstore2/AppStore/AppStore.DataAccessLayer/Logs/${shortdate}_log.txt" layout="${longdate} ${level:uppercase=true} ${message}"/>

</targets>

<rules>
  <logger name="*" minlevel="Trace" writeTo="logfile" final="true"/>
</rules>
Run Code Online (Sandbox Code Playgroud)

2)配置我的Programm.cs

public class Program
{
    public static void Main(string[] args)
    {
        var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();

        try
        {
            logger.Debug("init main"); …
Run Code Online (Sandbox Code Playgroud)

c# logging nlog asp.net-web-api asp.net-core

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

C# Web API 查询字符串中的可选参数

我的控制器中有这段代码:

[HttpGet]
[Route("team={team}&model={model}&date={date}&distance={distance}")]
public IHttpActionResult FindVehicle([FromUri]string team = "", [FromUri]string model = "", [FromUri]DateTime? date = null, [FromUri]double distance = 0.0)
    { }
Run Code Online (Sandbox Code Playgroud)

查询字符串的所有参数都可以是可选的,这就是我使用默认值的原因。

但是,我不确定路由应该是什么,因为现在,model例如,当我不指定参数时,它在端点中的值最终是"model",而不是""

c# http-get asp.net-web-api

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

无法解析 Microsoft.AspNetCore.Mvc.Razor.IRazorViewEngine 类型的服务

在我的项目中,core 2.2我有Razor View作为字符串返回的标准服务(我需要它在我的客户端中生成 pdf 编写的WPF):

public class RaportService : IRaportService
    {
        private readonly IProjectRepository projectRepository;
        private readonly IRazorViewEngine razorViewEngine;
        private readonly ITempDataProvider tempDataProvider;
        private readonly IServiceProvider serviceProvider;

        public RaportService(
            IProjectRepository projectRepository,
            IRazorViewEngine razorViewEngine,
            ITempDataProvider tempDataProvider,
            IServiceProvider serviceProvider)
        {
            this.projectRepository = projectRepository;
            this.razorViewEngine = razorViewEngine;
            this.tempDataProvider = tempDataProvider;
            this.serviceProvider = serviceProvider;
        }

        public async Task<string> GenerateProjectRaport(int projectId)
        {
            var project = await this.projectRepository.GetProjectWithTasksAsync(projectId)
                ?? throw new EntityNotFoundException();

            var httpContext = new DefaultHttpContext { RequestServices = …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-web-api asp.net-core asp.net-core-3.0

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