小编Loc*_*Loc的帖子

如何在ASP.NET Core 2中引发ForbiddenException,而不是使用AccessDeniedPath

我正在研究ASP.NET Core 2 Web应用程序。我正在处理[授权(角色或策略)]页面的“ 访问被拒绝页面。

默认情况下,ASP.NET Core 2.0 不会显示原始URL并返回403状态,而是将请求重定向到状态为302- >这不是我想要的AccessDenied页面。

而不是重定向AccessDenied页面。我希望ASP.NET Core抛出自定义的ForbiddenException异常,以便像处理未处理的异常一样处理未经授权的访问。

这是我的身份验证配置:

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; // Cookies
    options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; // Cookies       
    options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme; // Cookies
})
.AddCookie(options => {

    options.LoginPath = "/Auth/Login/";
    options.LogoutPath = "/Auth/Logout/";

    // I want disable this and throw ForbiddenException instead.
    options.AccessDeniedPath = "/Auth/AccessDenied/";  
});
Run Code Online (Sandbox Code Playgroud)

有人有帮助吗?谢谢!

c# authorize-attribute asp.net-authorization asp.net-core asp.net-core-2.0

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

如何在写入一些数据后重置 Asp.Net Core Response.Body

由于某些原因,我需要在中间件中写入一些数据后重置 Response.Body。

我在中间件调用方法中尝试过的:

if (!context.Response.HasStarted)
{
    // Not committed / data was not sent to client yet

    // Reset Response
    context.Response.StatusCode = StatusCodes.Status200OK;
    context.Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = null;

    if (context.Response.Body.CanSeek)
    {
        context.Response.Body.SetLength(0);
    }

    // Reset headers
    responseWrapper.ResetAddedHeaders()
}
Run Code Online (Sandbox Code Playgroud)

问题是 context.Response.HasStarted 始终为 TRUE,即使有几个字节从 Controller 操作写入 Response.Body。

我认为 Response Body 有一个内部缓冲区,所以除非内部缓冲区已满,否则 context.Response.HasStarted 必须为 FALSE。

有任何想法吗?谢谢!

asp.net-core-mvc .net-core asp.net-core

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

插页式广告是否有助于我们获得比横幅广告更多的收入?

我正在将Google AdMob添加到我的第一个Android应用程序中.我想知道我是否应该使用插页式广告.

我的问题是:插页式广告是否有助于我们获得比横幅广告更多的收入?

我的应用是一款教育应用.使用插页式广告有什么好的理由吗?

谢谢!

android ads adsense admob

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

如果服务器返回错误状态,java.net.HttpUrlConnection 是否总是抛出 IOException?

我正在使用java.net.HttpUrlConnection向我的服务器发出 Http 请求。我意识到如果服务器返回错误状态(例如 400)。HttpUrlConnection 将抛出与错误状态对应的 IOException。

我的问题是: 如果服务器返回错误状态(4xx、5xx),HttpUrlConnection 是否总是抛出 IOException?

我查看了HttpUrlConnection API 描述,但我无法回答我的问题。

更新:请看我的测试:

public static void main(String[] args) {
    try {
        
        String url = "https://www.googleapis.com/oauth2/v3/userinfo?access_token=___fake_token";
        HttpURLConnection conn = (HttpURLConnection)new URL(url).openConnection();
        
        conn.getResponseCode();
        conn.getInputStream();
        
    } catch (Exception ex) {
        ex.printStackTrace();
        // Print IOException: java.io.IOException: Server returned HTTP response code: 401 for URL: https://www.googleapis.com/oauth2/v3/userinfo?access_token=abc

        // If I commented conn.getResponseCode() -> The same IOException
    }
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

java exception http-status-codes httpurlconnection

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

实体框架核心显示警告消息

我的实体类别:

public class Unit
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int? UnitID { get; set; }

    public string Name { get; set; }

    [Required]
    public int? ManufacturerID { get; set; }

    // More fields

    public Manufacturer Manufacturer { get; set; }
}

public class Manufacturer
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int? ManufacturerID { get; set; }

    public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我的查询:

        return await DbContext.Unit.AsNoTracking().Include(r => r.Manufacturer)
                .Select(r => new
                {
                    UnitID = r.UnitID,
                    UnitName = r.Name,
                    ManufacturerName = r.Manufacturer.Name …
Run Code Online (Sandbox Code Playgroud)

entity-framework entity-framework-core .net-core asp.net-core entity-framework-core-2.1

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

Asp.Net Core和JWT身份验证:如何知道身份验证因令牌过期而失败?

以下是我正在使用的JWT身份验证:

.AddJwtBearer(options =>
{
    // options.SaveToken = false;
    // options.RequireHttpsMetadata = false;

    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(AuthConfig.GetSecretKey(Configuration)),

        ValidateIssuer = false,
        ValidateAudience = false,

        ValidateLifetime = true,
        ClockSkew = TimeSpan.Zero,
    };

    options.Events = new JwtBearerEvents()
    {
        OnChallenge = c =>
        {
            c.HandleResponse();

            // TODO: How to know if the token was expired?

            return AspNetUtils.WriteJsonAsync(c.Response, new Result<string> 
            { 
                Message = "Unauthenticated.", 
                IsError = true 
            }, 401);
        },
    };
});
Run Code Online (Sandbox Code Playgroud)

身份验证正常。对于新要求,我需要知道是否由于JWT令牌过期而导致身份验证失败。

请注意,身份验证失败可能有多种原因。令牌可能丢失,被篡改或过期。

有任何想法吗?谢谢!

jwt asp.net-core jwt-auth asp.net-core-2.1

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

一种有效的算法,可对小于一个大最大值(例如100_000)的4个唯一整数进行随机处理

这是我的尝试:

public static void main(String[] args) {
    // Max 100_000
    System.out.println(Arrays.toString(randomFour(100_000)));
}

public static int[] randomFour(int max) {
    Random r = new Random();
    int[] four = new int[4];

    for (int i = 0; i < 4; i++) {

        while (true) {
            // Random from 1 to max
            four[i] = 1 + (int) (r.nextFloat() * max);

            boolean dup = false; // check j: 0 -> i-1
            for (int j = 0; j < i; j++) {
                if (four[j] == four[i]) { …
Run Code Online (Sandbox Code Playgroud)

java random algorithm

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

我们是否应始终使用异步JAX-RS资源用于移动后端?

我正在使用Java EE - JAX-RS 2.0技术构建Mobile后端API.

由于大多数移动客户端消耗都是异步http调用

所以我的问题是: 我应该为所有JAX-RS资源使用异步功能吗?原因如果不是?

以下是模板Mobile Async API

@Path("/async_api")
public class AsyncResource {

    @GET
    @Path("/loadUsers")
    @Produces(MediaType.APPLICATION_JSON)
    public void loadUsers(@Suspended AsyncResponse asyncResponse) {

        //TODO: ManagedExecutorService

        new Thread(new Runnable() {

            @Override
            public void run() {
                List users = loadBigUsers();
                asyncResponse.resume(users);
            }

            private List loadBigUsers() {
                return null; // Return big list
            }

        }).start();
    }
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

java asynchronous jax-rs java-ee-7

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