我用EF6和我的Base存储库Save()看起来像这样
public void Save()
{
try
{
Context.SaveChanges();
}
catch (DbEntityValidationException ex)
{
//Do Stuff
}
catch (Exception exception)
{
//Do stuff.
}
else
{
throw;
}
}
Run Code Online (Sandbox Code Playgroud)
DbEntityValidationException
如果对象保存无效,则是EF的预期错误.现在我正在使用新的.NET Core 2项目,我需要知道EF Core中的预期实体验证错误类型是什么.
c# entity-framework entity-framework-core asp.net-core asp.net-core-2.0
我有一个服务,它在一个名为的方法中从文件中异步读取一些内容 InitAsync
public class MyService : IService {
private readonly IDependency injectedDependency;
public MyService(IDependency injectedDependency) {
this.injectedDependency = injectedDependency;
}
public async Task InitAsync() {
// async loading from file.
}
}
Run Code Online (Sandbox Code Playgroud)
现在这个服务被注入到我的控制器中。
public class MyController : Controller {
private readonly IService service;
public MyController(IService service) {
this.service = service;
}
}
Run Code Online (Sandbox Code Playgroud)
现在我想要一个 MyService 的单例实例。我想在启动时调用 InitAsync。
public class Startup {
public void ConfigureServices(IServiceCollection services) {
......
services.AddSingleton<IService, MyService>();
var serviceProvider = services.BuildServiceProvider();
// perform async init.
serviceProvider.GetRequiredService<IService>().InitAsync();
}
}
Run Code Online (Sandbox Code Playgroud)
发生的事情是在启动时,创建并 …
我有基于Angular v4的应用程序.场景很简单 - 我需要在应用程序启动之前从服务器加载一些设置.为此,我使用APP_INITIALIZER
:
{
provide: APP_INITIALIZER,
useFactory: init,
deps: [SettingsService],
multi: true
}
export function init(config: SettingsService) {
return () => config.load_one();
}
//import declarations
@Injectable()
export class SettingsService {
constructor(private http: HttpClient) { }
load_one(): Promise<boolean> {
return new Promise<boolean>((resolve) => {
this.http.get('url').subscribe(value => {
console.log('loadSettings FINISH');
resolve(true);
});
});
}
load_two(): Observable<any> {
const promise = this.http.get('url');
promise.subscribe(value => {
console.log('loadSettings FINISH');
});
return promise;
}
}
Run Code Online (Sandbox Code Playgroud)
在应用程序的某个地方,我有一个被调用的函数manageSettings()
(它的代码目前无关紧要),这需要SettingsService
初始化服务中的数据.
事情就是这样 - 当我使用该功能时 …
有没有办法向 IHttpClientFactory 创建的所有客户端添加处理程序?我知道您可以对指定客户执行以下操作:
services.AddHttpClient("named", c =>
{
c.BaseAddress = new Uri("TODO");
c.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
c.DefaultRequestHeaders.CacheControl = new CacheControlHeaderValue
{
NoCache = true,
NoStore = true,
MaxAge = new TimeSpan(0),
MustRevalidate = true
};
}).ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
{
AllowAutoRedirect = false,
AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip
});
Run Code Online (Sandbox Code Playgroud)
但我不想使用命名客户端,我只想向通过以下方式返回给我的所有客户端添加一个处理程序:
clientFactory.CreateClient();
Run Code Online (Sandbox Code Playgroud) 在 asp.net core 中,我可以使用中间件在此处描述的某些方法上启用 CORS
我想知道是否可以为任何方案和任何端口启用 CORS localhost
(仅用于测试目的)。我试过通配符,但它不起作用
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
if(_environment.IsDevelopment())
{
options.AddDefaultPolicy(
builder =>
{
builder.WithOrigins("http://localhost/*",
"https://localhost/*");
});
});
}
else
{
options.AddDefaultPolicy(
builder =>
{
builder.WithOrigins("http://example.com",
"http://www.contoso.com");
});
});
}
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
Run Code Online (Sandbox Code Playgroud) 我有一个Repository.cs
包含接口的文件及其实现如下:
public interface IRepository
{
IEnumerable<City> Cities { get; }
void AddCity(City newCity);
}
public class MemoryRepository : IRepository
{
private List<City> cities = new List<City> {
new City { Name = "London", Country = "UK", Population = 8539000},
new City { Name = "New York", Country = "USA", Population = 8406000 },
new City { Name = "San Jose", Country = "USA", Population = 998537 },
new City { Name = "Paris", Country = "France", Population = …
Run Code Online (Sandbox Code Playgroud) 对于学校项目,我需要使用Angular创建一个简单的登录页面.单击登录按钮时,我需要在帖子中添加Authorization标头.我创建了一个后端,当我使用邮递员将我的授权值发布到该后端时,它的工作方式与后端没有任何问题.当我尝试使用我的前端发布到同一个后端时,它不起作用.向帖子添加标题的最佳方法是什么?似乎意见分歧.这是我的代码:
export class LoginComponent{
title = 'Login';
email = '';
password = '';
credentials = '';
basic = '';
constructor(private http:HttpClient){
}
createAuthorizationHeader(headers:Headers,basic){
headers.append('Authorization',basic);
}
login(event){
this.email = (<HTMLInputElement>document.getElementById("email")).value;
this.password = (<HTMLInputElement>document.getElementById("password")).value;
this.credentials = this.email + ":" + this.password;
this.basic = "Basic " + btoa(this.credentials);
console.log(this.basic);
let headers = new Headers();
headers.append('Content-Type','application/json');
headers.append('Authorization',this.basic);
let options = new RequestOptions({headers:headers});
console.log(headers);
return this.http.post('http://localhost:8000/api/v1/authenticate',options)
.subscribe(
res =>{
console.log(res);
},
err => {
console.log(err.message);
}
)
}
}
Run Code Online (Sandbox Code Playgroud)
当我运行该代码时,我得到400状态响应并且不添加标头.
我正在尝试有条件地验证 MVC.NET Core 中的字段。我有两个单选按钮。如果我选择是(对于所有权),我想在下面设置一个字段(活动下拉菜单)
但是,无论我多么努力,要验证的值总是来自 Activity 字段,而不是来自 Ownership 字段(“N\A”而不是“Yes”)
有人可以告诉我我做错了什么吗
视图 (chtml)
<div class=" form-group">
<div class="bisformdynamiclabel"></div>
<br />
@Html.RadioButtonFor(model => model.BIS232Request.JSONData.OwnershipActivity.Ownership, "Yes", new { id = "OwnershipAnswer_true", onclick = "displayOwnershipFieldsRow(true)" })
<label for="OwnershipAnswer_true">Yes</label>
@Html.RadioButtonFor(model => model.BIS232Request.JSONData.OwnershipActivity.Ownership, "No", new { id = "OwnershipAnswer_false", onclick = "displayOwnershipFieldsRow(false)" })
<label for="OwnershipAnswer_false">No</label>
<span class="alert-danger">
@Html.ValidationMessage("OwnershipAnswer")
</span>
</div>
<div class="row ownershipfieldsrow">
<div class="col-xs-12 col-md-12">
<div class=" form-group">
<div class="bisformdynamiclabel"></div>
<br />
<input style="display:none" class="form-control" type="text" asp-for="BIS232Request.JSONData.OwnershipActivity.Activity" />
<select class="form-control ownershipactivityselect" onchange="$('#BIS232Request_JSONData_OwnershipActivity_Activity').val($(this).val()); ">
<option value="N/A">Please …
Run Code Online (Sandbox Code Playgroud) 到目前为止,我已经能够翻译 ASP.Net Core 2.1 Web 应用程序中的所有内容。
事实证明这是一个小挑战,因为脚手架帐户页面需要一些设置。
但是我找不到一种翻译密码验证消息的方法。此外,翻译模型绑定消息是一个小挑战(感谢 stackoverflow)。
有任何想法吗?
我包括我的Startup.cs
文件的相关部分:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddMvc(options =>
{
var type = typeof(SharedResources);
var assemblyName = new AssemblyName(type.GetTypeInfo().Assembly.FullName);
var factory = services.BuildServiceProvider().GetService<IStringLocalizerFactory>();
var L = factory.Create("SharedResources", assemblyName.Name);
options.ModelBindingMessageProvider.SetValueIsInvalidAccessor(x => L["The value '{0}' is invalid.", x]);
options.ModelBindingMessageProvider.SetValueMustNotBeNullAccessor(x => L["The value '{0}' is invalid.", x]);
options.ModelBindingMessageProvider.SetValueMustBeANumberAccessor(x => L["The field {0} must be a number.", x]);
options.ModelBindingMessageProvider.SetMissingBindRequiredValueAccessor(x => L["A value for the '{0}' property was not provided.", x]);
options.ModelBindingMessageProvider.SetAttemptedValueIsInvalidAccessor((x, y) …
Run Code Online (Sandbox Code Playgroud) 我正在创建一个弹出组件,我希望它是可移动的。我可以使用顶部/左侧样式移动它,但现在它们被初始化top:0;left:0;
,因此弹出窗口出现在页面的左上角。我希望让它出现在页面的中心,然后获取我的 div 的左上角坐标,以便在之后正确管理我的计算。
这是我现在所拥有的:
<div class="child-window" draggable="true" style="position:absolute; top: @(offsetY)px; left: @(offsetX)px; border-color: black;" @ondragend="OnDragEnd" @ondragstart="OnDragStart">
<div class="cw-content">
@Content
</div>
</div>
@code {
private double startX, startY, offsetX, offsetY;
protected override void OnInitialized() {
base.OnInitialized();
ResetStartPosition();
}
private void ResetStartPosition() {
//Set offsetX & offsetY to the top left div position
}
private void OnDragStart(DragEventArgs args) {
startX = args.ClientX;
startY = args.ClientY;
}
private void OnDragEnd(DragEventArgs args) {
offsetX += args.ClientX - startX;
offsetY += args.ClientY - …
Run Code Online (Sandbox Code Playgroud)