小编fee*_*per的帖子

注入DbContext时无法访问ASP.NET Core中的已处置对象

在ASP.NET Core项目中,我在Startup上有以下内容:

  services.AddDbContext<Context>(x => x.UseSqlServer(connectionString));

  services.AddTransient<IValidationService, ValidationService>();

  services.AddTransient<IValidator<Model>, ModelValidator>();
Run Code Online (Sandbox Code Playgroud)

ValidationService如下:

public interface IValidationService {
    Task<List<Error>> ValidateAsync<T>(T model);
}

public class ValidationService : IValidationService {
    private readonly IServiceProvider _provider;

    public ValidationService(IServiceProvider provider) {
        _provider = provider;
    }

    public async Task<List<Error>> ValidateAsync<T>(T model) {
        IValidator<T> validator = _provider.GetRequiredService<IValidator<T>>();

        return await validator.ValidateAsync(model);
    }
}
Run Code Online (Sandbox Code Playgroud)

ModelValidator如下:

public class ModelValidator : AbstractValidator<Model> {
  public ModelValidator(Context context) {
    // Some code using context
  }
}
Run Code Online (Sandbox Code Playgroud)

当我在控制器中注入IValidationService并将其用作:

List<Error> errors = await _validator.ValidateAsync(order);    
Run Code Online (Sandbox Code Playgroud)

我收到错误:

System.ObjectDisposedException:无法访问已处置的对象.此错误的常见原因是处理从依赖项注入解析的上下文,然后尝试在应用程序的其他位置使用相同的上下文实例.如果您在上下文中调用Dispose()或将上下文包装在using语句中,则可能会发生这种情况.如果使用依赖项注入,则应该让依赖项注入容器负责处理上下文实例.对象名称:'上下文'.

知道为什么我在ModelValidator中使用Context时遇到此错误.

如何解决这个问题?

UPDATE …

entity-framework-core asp.net-core

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

获取(415)不支持的媒体类型错误

我要做的是我必须在给定的URL中发布JSON数据我的JSON看起来像

{
    "trip_title":"My Hotel Booking",
    "traveler_info":{
        "first_name":"Edward",
        "middle_name":"",
        "last_name":"Cullen",
        "phone":{
            "country_code":"1",
            "area_code":"425",
            "number":"6795089"
        },
        "email":"asdv@gmail.com"
    },
    "billing_info":{
        "credit_card":{
            "card_number":"47135821",
            "card_type":"Visa",
            "card_security_code":"123",
            "expiration_month":"09",
            "expiration_year":"2017"
        },
        "first_name":"Edward",
        "last_name":"Cullen",
        "billing_address":{
            "street1":"Expedia Inc",
            "street2":"108th Ave NE",
            "suite":"333",
            "city":"Bellevue",
            "state":"WA",
            "country":"USA",
            "zipcode":"98004"
        },
        "phone":{
            "country_code":"1",
            "area_code":"425",
            "number":"782"
        }
    },
    "marketing_code":""
}
Run Code Online (Sandbox Code Playgroud)

而我的功能

string message = "URL";
_body="JSON DATA";
HttpWebRequest request = HttpWebRequest.Create(message) as HttpWebRequest;
if (!string.IsNullOrEmpty(_body))
{
    request.ContentType =  "text/json";
    request.Method =  "POST";

    using (var streamWriter = new StreamWriter(request.GetRequestStream()))
    {
        streamWriter.Write(_body);
        streamWriter.Flush();
        streamWriter.Close();
    }
} …
Run Code Online (Sandbox Code Playgroud)

c# post json http httpwebrequest

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

永久删除带有Web配置的HTML扩展

我试图使用web.config从页面中删除html扩展名.下面是我在web.config文件中使用的代码

<rewrite>
  <rules>
    <rule name="rewrite html">
      <match url="(.*)$" />
      <conditions logicalGrouping="MatchAll">
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
        <add input="{REQUEST_FILENAME}" negate="true" pattern="(.*).html" />
      </conditions>
      <action type="Rewrite" url="{R:1}.html" />
    </rule> 
  </rules>
</rewrite>
Run Code Online (Sandbox Code Playgroud)

它工作正常并删除html扩展,但这里似乎有2个问题:

  1. 当我把'斜杠'它不起作用,并给我没有发现错误.例如:http://example.com/my-page/现在它不起作用,但我放了http://example.com/my-page它会工作正常,所以我希望他们两个都能工作

  2. 其他问题是.html页面仍在打开.例如,如果我打开页面,因为http://example.com/my-page.html它也在工作,但我希望它http://example.com/my-page自动转换,我知道我可以使用301重定向,但这不会起作用,因为这里有很多文件,所以我必须使用不同的不同网址的301规则.

请指教.

谢谢

html iis redirect web-config

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

AttributeError: 在使用自定义生成器的 Keras 模型上调用 fit 时,'tuple' 对象没有属性 'rank'

我想构建一个具有两个输入的神经网络:用于图像数据和数字数据。所以我为此编写了自定义数据生成器。在trainvalidationdataframes包含11列:

  1. image_name — 图像路径;
  2. 9个数字特征;
  3. target — 项目的类(最后一列)。

自定义生成器的代码(基于此答案):

target_size = (224, 224)
batch_size = 1

train_datagen = ImageDataGenerator(
    rescale=1./255,
    rotation_range=20,
    width_shift_range=0.2,
    height_shift_range=0.2,
    horizontal_flip=True)

val_datagen = ImageDataGenerator(rescale=1./255)

train_generator = train_datagen.flow_from_dataframe(
    train,
    x_col='image_name',
    y_col=train.columns[1:],
    target_size=target_size,
    batch_size=batch_size,
    shuffle=True,
    class_mode='raw')

validation_generator = val_datagen.flow_from_dataframe(
    validation,
    x_col='image_name',
    y_col=validation.columns[1:],
    target_size=target_size,
    shuffle=False,
    batch_size=batch_size,
    class_mode='raw')

def train_generator_func():
    count = 0
    while True:
        if count == len(train.index):
            train_generator.reset()
            break
        count += 1
        data = train_generator.next()
        
        imgs = []
        cols = []
        targets = …
Run Code Online (Sandbox Code Playgroud)

python neural-network deep-learning keras tensorflow

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

Caliburn Micro中的墓碑

我有MainPageViewModel与Items(ObservableCollection).在这个页面上,我还有一个按钮,可以向项目中添加新项目.

public class MainPageViewModel : Screen {
  private DateTime StartActivity = DateTime.MinValue;

  public ObservableCollection<ActivityViewModel> Items { get; set; }

  public MainPageViewModel(INavigationService navigationService) {
    this.Items = new ObservableCollection<ActivityViewModel>();
  }

  public void AddActivity(string activityName) {
    if (this.Items.Count == 0) {
      this.Items.Add(new ActivityViewModel() { 
        Activity = activityName, 
        Duration = 0 
      });

      StartActivity = DateTime.Now;
      }
    else {
      this.Items[this.Items.Count - 1].Duration = 10;
      this.Items.Add(new ActivityViewModel() { 
        Activity = activityName,
        Duration = 0 
      });

      StartActivity = DateTime.Now;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

添加新项目非常有效.

但是,在逻辑删除后应用程序激活时,来自项目的数据无法恢复.尝试为我的ViewModel创建StorageHandler.没有帮助.我做错了什么?

public class MainPageViewModelStorage …
Run Code Online (Sandbox Code Playgroud)

windows-phone-7 caliburn.micro tombstoning

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

C#:扩展泛型类

partial class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{
}
Run Code Online (Sandbox Code Playgroud)

我的通用仓库实施一套共同的方法,TEntity

public TEntity Get(int id)
{
    return _context.Set<TEntity>()
        .Find(id);
}

public TEntity Get(Expression<Func<TEntity, bool>> predicate)
{
    return _context.Set<TEntity>()
}
Run Code Online (Sandbox Code Playgroud)

我可以访问

Repository<User>().Get();
Run Code Online (Sandbox Code Playgroud)

许多存储库执行相同的操作集,因此它是有益的,但现在我想扩展Repository<User>以支持一些额外的行为.

partial class Repository<User> : IRepository<User> 
{
    public user DoMagicFunction()
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

所以我可以像使用存储库一样

Repository<User>().DoMagicFunction();
Run Code Online (Sandbox Code Playgroud)

如何为Some扩展相同的泛型类Tentity以扩展新行为而不是修改它.

我本可以做同样的事情,比如创建另一个UserRepository来支持新功能,但访问者会变成

UserRepository.DoMagicFunction();
Run Code Online (Sandbox Code Playgroud)

但我希望它像

Repository<User>().DoMagicFunction();
Run Code Online (Sandbox Code Playgroud)

c# generics

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

我无法通过 pip 安装 kivy

我在通过 pip 安装 kivy 时遇到此错误,对此问题有什么帮助吗?

在此处输入图片说明

如果可以的话,我会提供有关错误的更多信息,但我什至不知道错误是什么,也不知道为什么会得到它。

python pip kivy

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

Python TimedRotatingFileHandler 覆盖日志

TimedRotatingFileHandler这样设置:

import logging as logging
from logging.handlers import TimedRotatingFileHandler
import os
import time

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

# new file every minute
rotation_logging_handler = TimedRotatingFileHandler('logs/log', 
                               when='m', 
                               interval=1, 
                               backupCount=5)
rotation_logging_handler.setLevel(logging.DEBUG)

format = u'%(asctime)s\t%(levelname)s\t%(filename)s:%(lineno)d\t%(message)s'
rotation_logging_handler.setFormatter(logging.Formatter(format))
rotation_logging_handler.suffix = '%Y-%m-%d'

logger.addHandler(rotation_logging_handler)
Run Code Online (Sandbox Code Playgroud)

用法:

logger.logging.info('Service started at port %s', config.get_param('port'))

while True:
    time.sleep(21)
    logger.logging.info('Now time is {}'.format(time.time()))
Run Code Online (Sandbox Code Playgroud)

我预计每分钟新消息都logs/log必须附加到当前日期的现有日志文件中。相反,它每分钟的消息都会logs/log覆盖当前日期的现有日志文件。

我应该怎么做才能达到这种行为?

PS:经过小研究,我发现该TimedRotatingFileHandler方法doRollover会删除现有日志文件并创建新文件。因此,第一个解决方案是创建新的处理程序,从中TimedRotatingFileHandler 创建新文件(例如带有一些索引),而不是删除现有日志文件。

python logging

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

尝试将List <object>转换为数组

我有一个类型为"Employee"类对象的列表,其中包含从数据库中检索的员工详细信息.

所有数据都被成功检索到列表,但是当我尝试将列表转换为JSON数组对象时,我遇到了奇怪的错误.

我用了两种方法来完成它,但它们都没有用.

这是完整的beind-code:

using System.Web.Script.Serialization;
using System.Web.Script.Services;
using Newtonsoft.Json;
Run Code Online (Sandbox Code Playgroud)

..

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string getRecords()
{
    SqlConnection con;
    SqlCommand cmd;
    SqlDataReader reader;
    List<Employee> dataRows = new List<Employee>();

    con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=\"C:\\Users\\Shebel Ali\\Desktop\\SampleDB.mdf\";Integrated Security=True;Connect Timeout=30");
    con.Open();
    cmd = con.CreateCommand();
    cmd.CommandText = "select * from Employee";

    reader = cmd.ExecuteReader();
    int i = 1;

    for (i=0; i<reader.FieldCount; i++)
    {
        Debug.WriteLine(reader.GetName(i));
    }


    while (reader.Read())
    {
        Employee getEmp = new Employee(reader.GetValue(0).ToString(), reader.GetValue(1).ToString(), reader.GetValue(2).ToString(), reader.GetValue(3).ToString(), reader.GetValue(4).ToString(), reader.GetValue(5).ToString(), reader.GetValue(6).ToString());
        dataRows.Add(getEmp);
    }

    JavaScriptSerializer js …
Run Code Online (Sandbox Code Playgroud)

c# arrays json

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