小编egm*_*frs的帖子

防止在移动设备上的输入字段中输入小数位

我有这个 javascript 代码,它在桌面浏览器上运行良好,可以确保用户只能输入字符 1 到 9。

然而,在 Android 上的 Chrome 中进行测试时,显示的键盘包含该字段接受的短划线和句点字符。我怎样才能防止这种情况发生?

    function isNumberKey(evt) {
        var charCode = (evt.which) ? evt.which : evt.keyCode;
        if (charCode > 31 && (charCode < 48 || charCode > 57))
            return false;
        return true;
    }
Run Code Online (Sandbox Code Playgroud)

更新:

这就是我在 HTML 中使用该函数的方式:

  <input type="number" class="form-control" 
         onkeypress="return isNumberKey(event)" />
Run Code Online (Sandbox Code Playgroud)

我有另一个函数来防止将非数字字符复制并粘贴到代码中。

    $(document).ready(function() {
        $('#number').bind("cut copy paste drag drop", function(e) {
            e.preventDefault();
        });     
    });
Run Code Online (Sandbox Code Playgroud)

如果其他方法都失败了,还有服务器端验证。

我真的很想阻止前端出现小数位。请记住,我指定的字符范围在 qwerty 键盘上限制了这一点 - 但是在 Android(可能还有其他)上,数字键盘允许输入.-

html javascript jquery android google-chrome

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

在POST API中传递多个参数,而不使用.Net Core MVC中的DTO类

我在我的web项目上有一个调用API的操作

    [HttpPost]
    public async Task<IActionResult> ExpireSurvey(int id)
    {
        var token = await HttpContext.GetTokenAsync("access_token");

        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);

            var path = "/api/forms/ExpireSurvey";
            var url = Domain + path;
            var data = JsonConvert.SerializeObject(id);
            HttpContent httpContent = new StringContent(data, Encoding.UTF8, "application/json");
            var response = await client.PutAsync(url, httpContent);

            return Json(response);
        }
    }
Run Code Online (Sandbox Code Playgroud)

在API项目中,收到如下:

[HttpPut]
    public IActionResult ExpireSurvey([FromBody] int surveyId)
    {
        _repository.ExpireSurvey(surveyId, expiryDate);
        return Ok();
    }
Run Code Online (Sandbox Code Playgroud)

这工作正常 - 但是,我想要传入一个int id和一个DateTime变量,我如何序列化并将它们传递给HttpContent?我可以用DTO对象来做,但是当只有两个字段时我不想设置DTO对象.

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

5
推荐指数
3
解决办法
7094
查看次数

在不丢弃数据的情况下重命名Entity Framework Core中的外键

我有两个模型类:

public class Survey
{
    public int SurveyId { get; set; }
    public string Name { get; set; }
}

public class User
{
    public int UserId { get; set; }

    public int SurveyId { get; set; }
    public Survey Survey { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我要重命名SurveyStudentSurvey,所以就会产生StudentSurveyId.我相应地更新了模型中的类名和属性,并添加了一个迁移.

但是,我得到:

ALTER TABLE语句与FOREIGN KEY约束"FK_User_Surveys_SurveyId"冲突.冲突发生在数据库"AppName",表"dbo.Survey",列"SurveyId"中.

我认为它试图删除数据,因为它需要列中的数据(不能为空)我看到了这个错误.但我不想丢弃数据.我怎样才能重命名呢?

c# sql-server entity-framework entity-framework-core ef-core-2.0

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

如何在.net Core 2.0中扩展SignInManager

我在用户类(IsEnabled)中设置了一个新属性,并希望登录管理器对此进行检查,因此我按如下方法重写PasswordSignInAsync:

public class AuthSignInManager<TUser> : SignInManager<User> where TUser : class
{
    private readonly UserManager<User> _userManager;
    private readonly AuthContext _db;
    private readonly IHttpContextAccessor _contextAccessor;

    public AuthSignInManager(
        UserManager<User> userManager, 
        IHttpContextAccessor contextAccessor, 
        IUserClaimsPrincipalFactory<User> claimsFactory, 
        IOptions<IdentityOptions> optionsAccessor, 
        ILogger<SignInManager<User>> logger, 
        AuthContext dbContext,
        IAuthenticationSchemeProvider schemeProvider
        )
        : base(userManager, contextAccessor, claimsFactory, optionsAccessor, logger, schemeProvider)
    {
        _userManager = userManager ?? throw new ArgumentNullException(nameof(userManager));
        _contextAccessor = contextAccessor ?? throw new ArgumentNullException(nameof(contextAccessor));
        _db = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
    }

    public override Task<SignInResult> PasswordSignInAsync(string userName, string password, bool rememberMe, bool …
Run Code Online (Sandbox Code Playgroud)

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

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

当字段设置为必需时,EF inMemory 提供程序错误地接受空条目

这是我的集成测试代码:

[Fact(DisplayName = "Should only add AssetType when Name Provided")]
public async Task Test4()
{
    using (var context = GetContext()) {

        var listAssetTypes = await context.AssetType.ToListAsync();

        Assert.Equal(0, listAssetTypes.Count);

        var goodAssetType = new AssetType { Name = "1st Item" };
        context.Add(goodAssetType);
        await context.SaveChangesAsync();
        listAssetTypes = await context.AssetType.ToListAsync();

        Assert.Equal(1, listAssetTypes.Count);

        var badAssetType = new AssetType {};
        context.Add(badAssetType);
        await context.SaveChangesAsync();
        listAssetTypes = await context.AssetType.ToListAsync();

        Assert.Equal(1, listAssetTypes.Count);
    }
}
Run Code Online (Sandbox Code Playgroud)

前两个断言通过。第三次失败,实际为 2,如果我调试,我可以看到一个新的 Id 已分配,名称设置为空。

这是我的上下文方法:

private WorldContext GetContext()
{
    var builder = new ConfigurationBuilder();
    var …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-mvc unit-testing entity-framework

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

拦截asp.net核心授权操作以在成功授权后执行自定义操作

我的网络应用控制器上有[授权]属性,因此任何端点命中都会确保用户首先被重定向到登录OAuth服务器(如果尚未登录).

我现在想要在用户每次登录时开始将用户声明写入Web应用程序数据库.为此,我需要在每次用户成功登录/授权时在Web应用程序上运行一些代码.

我得到了一个线索,它涉及添加自定义中间件.

我的启动ConfigureServices代码目前如下:

public class Startup
{
    public Startup(IConfiguration configuration, IHostingEnvironment env)
    {
        Configuration = configuration;
        Env = env;
    }

    public IHostingEnvironment Env { get; }
    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {

        services.AddMvc();

        // Adds a default in-memory implementation of IDistributedCache.
        services.AddDistributedMemoryCache();

        services.AddSession(options =>
        {
            options.Cookie.HttpOnly = true;
        });

        JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

        services.AddAuthentication(options =>
        {
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
        })
            .AddCookie()
            .AddOpenIdConnect(options =>
            {
                options.SignInScheme = "Cookies";
                options.Authority = Configuration["auth:oidc:authority"];                    

                options.RequireHttpsMetadata = !Env.IsDevelopment();
                options.ClientId …
Run Code Online (Sandbox Code Playgroud)

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

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

在.NET Core 2.0中创建全局变量以在剃刀视图中使用

我的应用程序中有一个按钮出现在多个页面上。(从不同控制器调用的页面。)

<a ... class="btn btn-primary">Complete New Survey</a>
Run Code Online (Sandbox Code Playgroud)

我想将“完成新调查”按钮中的文本设置为全局变量。好像客户希望这是“开始新调查”,我不想在整个应用程序中进行查找和替换。

我希望能够做类似的事情:

<a ... class="btn btn-primary">@GlobalVars["NewSurveyButton"]</a>
Run Code Online (Sandbox Code Playgroud)

并将其定义在文件中的某个位置,例如:

GlobalVars["NewSurveyButton"] = "Start new survey"
Run Code Online (Sandbox Code Playgroud)

c# asp.net-core

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