我试图弄清楚如何通过HTTP连接(与https相对)进行调用时返回错误请求。我唯一能弄清楚如何做到这一点的方法是编写中间件并以以下方式检查每个请求:
public class HttpRequestInterceptor
{
private readonly RequestDelegate _next;
public HttpRequestInterceptor(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
var scheme = context.Request.Scheme;
if (scheme.Equals("http", StringComparison.InvariantCultureIgnoreCase))
{
context.Response.StatusCode = 400;
context.Response.ContentType = "application/json";
await context.Response.WriteAsync("{\"result:\" \"Bad Request\"}", Encoding.UTF8);
return;
}
await _next.Invoke(context);
}
}
有更好的方法吗?也许是通过框架的内置方式?
答案 0 :(得分:2)
您可以通过源自RequireHttpsAttribute来创建像this这样的自定义过滤器:
/// <summary>
/// An authorization filter that closes connections if they are not secure (HTTPS).
/// Be aware that sensitive information sent by the client WILL be visible!
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class RequireHttpsOrCloseAttribute : RequireHttpsAttribute
{
protected int StatusCode { get; }
/// <summary>
/// Return a status result with the given status code when the request does not use HTTPS.
/// </summary>
/// <param name="statusCode"></param>
public RequireHttpsOrCloseAttribute(int statusCode)
{
StatusCode = statusCode;
}
/// <summary>
/// Return a 400 Bad Request status code result when the request does not use HTTPS.
/// </summary>
public RequireHttpsOrCloseAttribute()
: this(400)
{
}
/// <summary>
/// Sets the status result to the appropriate StatusCodeResult specified in the constructor.
/// The default is 400 Bad Request.
/// </summary>
/// <param name="filterContext"></param>
protected override void HandleNonHttpsRequest(AuthorizationFilterContext filterContext)
{
filterContext.Result = new StatusCodeResult(StatusCode);
}
}
然后您可以在应用程序中全局注册它:
services.AddMvc(opt =>
{
opt.Filters.Add(new RequireHttpsOrCloseAttribute())
});