我在表单中的 cshtml 页面中有一个典型的 div 元素:
<div id="loginErrors" class="alert alert-danger hide-errors">@(ErrorMessage)</div>
Run Code Online (Sandbox Code Playgroud)
在 Blazor 之前,我通常使用 jQueryhide-errors在 div 中添加或删除类。但是,Blazor 正试图消除对 JavaScript 的需求,我正在尝试尽可能少地使用 JSInterop。Blazor 有没有办法做到这一点?
所以在 Blazor 我可以这样做:
@if (!string.IsNullOrEmpty(ErrorMessage))
{
<div id="loginErrors" class="alert alert-danger">@(ErrorMessage)</div>
}
else
{
<div id="loginErrors" class="alert alert-danger hide-errors">@(ErrorMessage)</div>
}
Run Code Online (Sandbox Code Playgroud)
或使用 JSinterop :
要求删除:
await JSRuntime.Current.InvokeAsync<object>("blazorExtensions.RemoveClass", "loginErrors", "hide-errors");
Run Code Online (Sandbox Code Playgroud)
函数通常是:
RemoveClass: function (id, classname) {
var tt = '#' + id;
$(tt).removeClass(classname);
}
Run Code Online (Sandbox Code Playgroud)
与添加类类似。上述两项工作,但如上所述。我试图避免 JSInterop 路由,我不喜欢 div 元素被声明两次,即使只有一个会进入 DOM。
我有一个登录页面,该页面会转到服务器获取一堆数据,然后我想获取其中的一些数据并使用客户端上的 Blazor 将其保存到 cookie 中。
所以首先我已经成功注入了 IHttpContextAccessor。现在在我的 Blazor 函数中,我有:
httpContextAccessor.HttpContext.Response.Cookies.Append("test", "ddd");
在调试中,当我点击上面的代码行时,它会出错:
“标题是只读的,响应已经开始。”
当然,我不会在 cookie 中使用“ddd”保存“test”,我现在只是想获取一个 cookie 来保存。
我有以下标记(xaml):
<ListBox Name="lbEurInsuredType" HorizontalContentAlignment="Stretch">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Margin="0,2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"></ColumnDefinition>
<ColumnDefinition Width="30"></ColumnDefinition><ColumnDefinition Width="2"></ColumnDefinition>
<ColumnDefinition Width="30"></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Title}"></TextBlock>
<TextBox Text="{Binding Uw}" Grid.Column="1"></TextBox>
<TextBox Text="{Binding Partner}" Grid.Column="3"></TextBox>
</Grid>
</DataTemplate></ListBox.ItemTemplate>
</ListBox>
Run Code Online (Sandbox Code Playgroud)
这一切看起来还不错,但现在在第1列和第3列之上,我想放置一个标题.任何人都可以告诉我如何将标题添加到我的两列.
在我的配置方法的startup.cs文件中,我有以下内容:
public void Configure(IApplicationBuilder app)
{
if (HostingEnvironment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
//TODO: Create an exception handler controller...
app.UseExceptionHandler("/Home/Error");
}
// app.UseRewriter(new RewriteOptions().AddRedirectToHttpsPermanent()); //required to force URL to https
app.UseStaticFiles();
app.UseSession();
app.UsePartialPageRendering();
app.Use(async (context, next) =>
{
await next.Invoke();
if (context.Response.StatusCode == 401)
{
context.Response.Redirect("/user/sign-in");
}
});
app.UseMvc();
// Log the environment so we can tell if it is correct.
Logger.LogInformation($"Hosting environment: {HostingEnvironment.EnvironmentName}");
}
Run Code Online (Sandbox Code Playgroud)
然后在授权过滤器中我有一些代码,在某些情况下我有:
var authorisationCookie = _httpContext.HttpContext.Request.Cookies.Where(t => t.Key == "aut").FirstOrDefault();
//no valid cookie
if (authorisationCookie.Key == …Run Code Online (Sandbox Code Playgroud) 我已经开始编写动态构建 RenderFragment 元素的方法。因此,我也在尝试在方法旁边编写单元测试。
我从一个非常基本的元素开始,但它失败了。下面是具体的测试方法:
public RenderFragment buildFragment(string element, string elementContent, string[] attribute, string[] attributeContent)
{
RenderFragment content = builder => {
builder.OpenElement(0, element);
if (attribute != null)
{
for (int i = 0; attribute.Length - 1 >= i; ++i)
{
builder.AddAttribute(0, attribute[i], attributeContent[i]);
}
}
if (!string.IsNullOrEmpty(elementContent))
{
builder.AddContent(0, elementContent);
}
builder.CloseElement();
};
return content;
}
Run Code Online (Sandbox Code Playgroud)
这是我对使用 xUnit 的方法的第一个基本测试:
public void BuildFragmentReturnsOneElement()
{
//Arrange
RenderFragment fragment = builder =>
{
builder.OpenElement(0, "p");
builder.CloseElement();
};
//Act
RenderFragment result = _dynamicContentHelper.buildFragment("p", string.Empty, …Run Code Online (Sandbox Code Playgroud) 我们有一个通用服务来发出和接收对后端控制器的调用。在 Angular 4 中,所有测试都有效,但由于新的库和更改,它们不再有效。HttpClientTestingModule我现在正在尝试使用和重写这些HttpTestingController。
所以我们的具体类有许多函数,目前我专注于我们的getRequest方法:
constructor(
private configService: ConfigService,
private userService: UserService,
private httpClient: HttpClient,
private errorMapperService: ErrorMapperService) {
}
public getRequest(uri: string): Observable<any> {
const fullUri = this.buildServiceUri(uri);
const requestHeaders = this.getDefaultRequestHeadersObservable();
return forkJoin(fullUri, requestHeaders)
.pipe(flatMap((results: [string, HttpHeaders]) => this.httpClient.get(results[0], { withCredentials: true, headers: results[1] })),
catchError(this.errorMapperService.handleError));
}
Run Code Online (Sandbox Code Playgroud)
目前在我的规范文件中我有:
fdescribe('Api Service', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
HttpClientModule,
HttpClientTestingModule
],
providers: [
{ provide: ApiService },
{ provide: ConfigService }, …Run Code Online (Sandbox Code Playgroud) 我有以下方法:
public async Task<SecurityRoleDeleteResult> DeleteSecurityRoleByRoleId(int securityRoleId)
{
string url = $"{_housingDataSecurityConfiguration.HousingDataSecurityWebApiUrl}SecurityRoles/Delete";
HttpResponseMessage message = _apiClientService.Post(url, securityRoleId);
if (message.StatusCode == HttpStatusCode.InternalServerError)
{
return SecurityRoleDeleteResult.ErrorOccurred;
}
int intResult = 0;
var apiResult = await message.Content.ReadAsStringAsync();
if (int.TryParse(apiResult, out intResult))
{
return (SecurityRoleDeleteResult)intResult;
}
else
{
return SecurityRoleDeleteResult.ErrorOccurred;
}
}
Run Code Online (Sandbox Code Playgroud)
我现在正尝试为其编写单元测试,到目前为止:
[Test]
public async Task DeleteSecurityRoleByRoleId()
{
_mockApiClientService.Setup(a => a.Post(It.IsAny<string>(), It.IsAny<int>()))
.Returns(new HttpResponseMessage {StatusCode = HttpStatusCode.OK});
SecurityRoleDeleteResult result = await _securityRoleService.DeleteSecurityRoleByRoleId(It.IsAny<int>());
Assert.AreEqual(SecurityRoleDeleteResult.Success, result);
}
Run Code Online (Sandbox Code Playgroud)
这里的问题是,当_securityRoleService.DeleteSecurityRoleByRoleId我尝试在方法中运行测试时,我试图将var apiResultmessage.content 设置为null,因为在这种情况下,我只是在嘲笑,所以崩溃了。
我怎样才能模拟出来,这样我的测试才能起作用?
我在许多MVC示例中看到如何ConfigurationServices在StartupClass 的方法中注册接口.当您的代码全部写在MVC应用程序中时,这很好,但在"真实世界"中,情况不一定如此.
我在表单中有一个类库项目
public class MyService : IMyService
{
private readonly IMyRepository _myRepository;
public MyService(IMyRepository myRepository)
{
_myRepository = myRepository;
}
.......
Run Code Online (Sandbox Code Playgroud)
现在在我的控制器中我有一个形式的构造函数:
public HomeController(IConfigurationRoot config, IMyServcie myService)
{
......
Run Code Online (Sandbox Code Playgroud)
问题是,MyService接口还没有在DI容器中注册,我真的不想ConfigurationServices用services.AddScoped<interface,class>()我的其他层的代码行填充方法.
我需要在其他层(存储库和服务)中首先在这里注册它们(两者都是.NET Core类库项目),然后将这些容器连接到父容器中?
一切正常,直到我介绍身份.
我将上下文类更改为:
public partial class VisualJobsDbContext : IdentityDbContext<ApplicationUser>
{
private IConfigurationRoot _config;
public VisualJobsDbContext() { }
public VisualJobsDbContext(IConfigurationRoot config, DbContextOptions options) : base(options)
{
_config = config;
}...
Run Code Online (Sandbox Code Playgroud)
我有一个在表单中声明的通用存储库:
public abstract class GenericRepository<C,T> : IGenericRepository<T> where T : class where C : IdentityDbContext<ApplicationUser>, new()
{
private C _entities = new C();
private VisualJobsDbContext context;
private DbSet<T> dbSet;
public GenericRepository(VisualJobsDbContext context)
{
this.context = context;
this.dbSet = context.Set<T>();
}....
Run Code Online (Sandbox Code Playgroud)
错误发生在
this.dbSet = context.Set <>();
它第一次被击中.我的OnModelCreating方法确实被调用了.我试图从我的MVC应用程序访问的页面不需要登录,因为它是一般页面,但是会有需要登录的区域.但是,在错误之前,我没有得到我的控制器Constructor方法.注册我的服务:
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<VisualJobsDbContext>()
.AddDefaultTokenProviders();
Run Code Online (Sandbox Code Playgroud)
我可以踩到这个.
我缺少什么想法?我看过这个 …
我正在尝试创建一个 gsub 管道,但在此之前我尝试按照互联网上的许多示例来模拟它。这是我的代码:
PUT _ingest/pipeline/removescript/_simulate
{
"pipeline" :{
"description": "remove script",
"processors": [
{ "gsub" :{
"field": "content",
"pattern": "(?:..)[^<%]+[^%>](?:..)",
"replacement": ""
}
}]
},
"docs": [
{
"_id": "tt",
"_source": {
"content": "leave <% remove me %> Me"
}
}]
}
Run Code Online (Sandbox Code Playgroud)
但是,当我运行它时,我收到以下错误:
找不到 uri [/_ingest/pipeline/removescript/_simulate] 和方法 [PUT] 的处理程序
如果我将 PUT 行更改为:
PUT _ingest/pipeline/_simulate或PUT _ingest/pipeline/removescript
然后我收到以下错误:
{
"error": {
"root_cause": [
{
"type": "parse_exception",
"reason": "[processors] required property is missing",
"header": {
"property_name": "processors"
}
}
],
"type": …Run Code Online (Sandbox Code Playgroud) c# ×7
blazor ×3
asp.net-mvc ×2
angular ×1
asp.net-core ×1
jasmine ×1
listbox ×1
moq ×1
nunit ×1
typescript ×1
unit-testing ×1
wpf ×1
xunit ×1