简体   繁体   English

如何将.NetFramework 中的MessageHandler 转换为AspNet.Core

[英]How to convert MessageHandler in .NetFramework to AspNet.Core

I have below message handler to return some custom messages, and I am registering in WebAPIConfig.Register method in.NetFramework, but I am having troubles with.Net Core as it looks like message handlers are removed in .NET core, I am getting some issues converting it.我有下面的消息处理程序来返回一些自定义消息,并且我正在.NetFramework 中的 WebAPIConfig.Register 方法中注册,但是我在使用.Net Core 时遇到了问题,因为看起来 .NET 核心中删除了消息处理程序,我遇到了一些问题转换它。

    public class WebApiCustomMessageHandler : DelegatingHandler
    {
        protected override async Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request, CancellationToken cancellationToken)
        {

            HttpResponseMessage response = await base.SendAsync(request, cancellationToken);

            if (response.StatusCode == HttpStatusCode.NotFound)
            {
                request.Properties.Remove(HttpPropertyKeys.NoRouteMatched);
                var errorResponse = request.CreateResponse(response.StatusCode, "resource not found.");
                return errorResponse;
            }

            return response;
        }
    }

registering in WebAPIConfig.Register method:在 WebAPIConfig.Register 方法中注册:

    public static void Register(HttpConfiguration config)
    {
      config.MessageHandlers.Add(new WebApiCustomMessageHandler());
    }

.NET Core implementation: .NET 核心实现:

I have below code but it gives errors on creating response and and returning it.我有以下代码,但它在创建响应和返回它时出错。

        public class WebApiCustomMiddleware
        {
            private readonly RequestDelegate _next;
    
            public WebApiCustomMiddleware(RequestDelegate next)
            {
                _next = next;
            }
    
            public async Task Invoke(HttpContext context)
            {
                //process context.Request
    
                await _next(context);

                //process context.Response
    
                if (context.Response.StatusCode == HttpStatusCode.NotFound)
                {
                   context.Request.Properties.Remove(HttpPropertyKeys.NoRouteMatched);
                   var errorResponse = context.Request.CreateResponse(context.Response.StatusCode, "resource not found.");
                   return errorResponse;
                }
                 
               return response;
                  
            }
        }

How do I create response and return in .net core middleware it is giving errors as it doesn't have context.Request.Properties, context.Request.CreateResponse, and also what would be the return type?如何在 .net 核心中间件中创建响应并返回它会给出错误,因为它没有 context.Request.Properties、context.Request.CreateResponse,以及返回类型是什么?

context.Request.Properties.Remove(HttpPropertyKeys.NoRouteMatched);
var errorResponse = context.Request.CreateResponse(context.Response.StatusCode, "resource not found.");
return errorResponse;

Please suggest.请建议。

Below is the Implementation (thanks to @King King):以下是实现(感谢@King King):

    public class WebApiCustomMiddleware
    {
        private readonly RequestDelegate _next;

        public WebApiCustomMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            //process context.Request
            //to do like validating api keys, request headers etc..

            await _next(context);

            //process context.Response
            if (context.Response.StatusCode == (int)HttpStatusCode.NotFound)
            {
                context.Response.ContentType = "application/json";
                await context.Response.WriteAsync(JsonConvert.SerializeObject(new
                {
                    statusCode = 404,
                    message = "resource not found"
                }));
            }
            else if(...)
            {}
        }
    }

And register in statup.cs并在 statup.cs 中注册

public void Configure(IApplicationBuilder app)
{
   app.UseMiddleware<WebApiCustomMiddleware>();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 AspNet.Core 中读取 EXIF 数据 - How can i read EXIF data in AspNet.Core 如何在aspnet.core web api中验证JWT令牌? - How to validate JWT Token in aspnet.core web api? 用于集成测试的ASPNet.Core HostingEnvironment? - ASPNet.Core HostingEnvironment for Integration Tests? 如何在ASPNET.Core Web应用程序中使用CORS标头发送HTTP 4xx-5xx响应? - How to send an HTTP 4xx-5xx response with CORS headers in an ASPNET.Core web app? 如何在Aspnet.core Razor中的foreach循环中使用Model动态填充HTML? - How to populate HTML dynamically with Model in a foreach loop in Aspnet.core Razor? 如何使用[HttpGetAttribute]路由包括AspNet.Core WebApi应用程序中的查询字符串? - How to route using [HttpGetAttribute] including the query strings in AspNet.Core WebApi application? Aspnet.core 程序登录但考虑同一个表中的数据 - The Aspnet.core program logs in but considers the data in the same table 在As.net.Core 中,我们可以更改端口号吗? - In Aspnet.Core, can we change port number? 是否可以为ASPNET.Core OData声明多个路由 - Is it possible to declare multiple routes for ASPNET.Core OData ASPNet.Core 从引用的程序集中读取 appsettings? - ASPNet.Core reading appsettings from referenced assemblies?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM