相关疑难解决方法(0)

用于设置响应ContentType的中间件

在我们基于ASP.NET Core的Web应用程序中,我们需要以下内容:某些请求的文件类型应该获得自定义ContentType的响应.例如.map应该映射到application/json.在"完整"的ASP.NET 4.x中,与IIS结合使用,可以使用web.config <staticContent>/<mimeMap>,我希望用自定义的ASP.NET Core中间件替换此行为.

所以我尝试了以下(简化为简洁):

public async Task Invoke(HttpContext context)
{
    await nextMiddleware.Invoke(context);

    if (context.Response.StatusCode == (int)HttpStatusCode.OK)
    {
        if (context.Request.Path.Value.EndsWith(".map"))
        {
            context.Response.ContentType = "application/json";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,尝试context.Response.ContentType在调用其余的中间件链后设置会产生以下异常:

System.InvalidOperationException: "Headers are read-only, response has already started."
Run Code Online (Sandbox Code Playgroud)

如何创建解决此要求的中间件?

c# owin-middleware asp.net-core asp.net-core-1.0

16
推荐指数
2
解决办法
4826
查看次数

自定义404响应模型

我想为我们的API上的所有404提供自定义响应.例如:

{
  "message": "The requested resource does not exist. Please visit our documentation.."
}
Run Code Online (Sandbox Code Playgroud)

我相信以下结果过滤器适用于MVC管道中的所有情况:

public class NotFoundResultFilter : ResultFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext context)
    {
        var result = context.Result as NotFoundResult;

        if (result != null)
        {
            context.Result = new HttpNotFoundResult(); // My custom 404 result object
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,当请求的URL与操作路由不匹配时,不会触发上面的过滤器.我怎样才能最好地拦截这404条回复? 这需要中间件吗?

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

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