In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article Xiaobian introduces in detail ".NetCore Web Api how to use the ActionFilterAttribute unified interface return value format", the content is detailed, the steps are clear, and the details are handled properly. I hope this article ".NetCore Web Api how to use the ActionFilterAttribute unified interface return value format" article can help you solve your doubts.
.net Core has several filters like Asp.Net MVC, and the order and function of each filter will not be discussed here.
In the actual project development process, a unified API return value format for front-end or third-party calls will be very necessary, in .NetCore we can use ActionFilterAttribute to encapsulate the unified return value.
We need to consider the following issues before encapsulation:
1. Which results need to be encapsulated?
My current practice is that only ObjectResult is encapsulated, and other types: FileResult,ContentResult,EmptyResult,RedirectResult are not handled.
2. Encapsulation of exception errors
Since it is a unified return value, of course, the problem of interface exception should also be considered.
But not all exceptions need to be returned to the front end. We may need to customize a business exception. Business exceptions can be prompted amicably at the front end. There is no need for system exceptions to be thrown to the front end or to a third party, and system exceptions need to be logged.
Project structure:
Exceptions: custom business exception
Filters: custom filter (uniform result encapsulation, global exception)
Models: unified result entity
Part of the code:
Using System; namespace NetCoreCommonResult.Exceptions {/ Custom business exception. The front end can throw a friendly prompt / public class BizException:Exception {public BizException () {} public BizException (string message): base (message) public BizException (string message, Exception ex): base (message, ex)}} using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.Filters Namespace NetCoreCommonResult.Filters {public class CommonResultFilterAttribute: ActionFilterAttribute {public override void OnResultExecuting (ResultExecutingContext context) {if (context.Result is ObjectResult objRst) {if (objRst.Value is Models.ApiResult) return Context.Result = new ObjectResult (new Models.ApiResult {Success = true, Message = string.Empty, Data = objRst.Value});} using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.Filters;using Microsoft.Extensions.Logging Namespace NetCoreCommonResult.Filters {public class GlobalExceptionFilterAttribute: ExceptionFilterAttribute {private readonly ILogger _ logger; public GlobalExceptionFilterAttribute (ILogger logger) {_ logger = logger;} public override void OnException (ExceptionContext context) {context.ExceptionHandled = true; var isBizExp = context.Exception is Exceptions.BizException Context.Result = new ObjectResult (new Models.ApiResult {Success = false, Message = context.Exception.Message}) / / non-business exception record errorLog, which returns 500status code. The frontend prompts if (isBizExp = = false) {_ logger.LogError (context.Exception, context.Exception.Message); context.HttpContext.Response.StatusCode = 500;} base.OnException (context);} by capturing the 500status code.
Startup.cs
Using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Hosting;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Hosting; namespace NetCoreCommonResult {public class Startup {public Startup (IConfiguration configuration) {Configuration = configuration;} public IConfiguration Configuration {get;} / / This method gets called by the runtime. Use this method to add services to the container. Public void ConfigureServices (IServiceCollection services) services.AddLogging (); services.AddControllers (ops = > {/ / add filter ops.Filters.Add (new Filters.CommonResultFilterAttribute () / / to inject other services into the GlobalExceptionFilterAttribute construction, you need to add ops.Filters.Add (new Microsoft.AspNetCore.Mvc.ServiceFilterAttribute (typeof (Filters.GlobalExceptionFilterAttribute);}) through ServiceFilter; / / register GlobalExceptionFilterAttribute services.AddScoped (); / / This method gets called by the runtime. Use this method to configure the HTTP request pipeline. Public void Configure (IApplicationBuilder app, IWebHostEnvironment env) if (env.IsDevelopment ()) app.UseDeveloperExceptionPage ();} else app.UseExceptionHandler ("/ Error"); app.UseStaticFiles (); app.UseRouting (); app.UseAuthorization (); app.UseEndpoints (endpoints = > endpoints.MapControllers () }}
Finally, create a new Controller and write several Action with different return values.
Using Microsoft.AspNetCore.Mvc;using System;using System.Collections.Generic;using System.Text;using System.Threading.Tasks; namespace NetCoreCommonResult.Controllers {[Route ("api/ [controller]")] [ApiController] public class HomeController: ControllerBase {/ string / [HttpGet] public string Index () = > "Welecome to .NetCore" / / Jump, do not process [HttpGet ("redirect")] public ActionResult Redirect () = > RedirectToAction ("Index"); / / [HttpGet ("num")] public int Num () = > 10; / / Asynchronous [HttpGet ("async")] public Task TaskString () = > Task.FromResult (new [] {"A", "B", "C"}) / / File output, do not handle [HttpGet ("file")] public ActionResult GetFile () = > File (Encoding.UTF8.GetBytes ("File String"), "text/plain"); / / empty return value, do not deal with [HttpGet ("empty")] public ActionResult Empty () = > Empty () / / contentResult does not handle [HttpGet ("content")] public ActionResult Content () = > Content ("this is content"); / exception returns 500error [HttpGet ("exception")] public ActionResult GetException () = > throw new InvalidOperationException ("invalid") / / Custom exception. Return 200 [HttpGet ("bizException")] public ActionResult GetBizException () = > throw new Exceptions.BizException ("bizException");}}
The following is a screenshot of the returned result:
Image above: results of accessing / api/home and / api/home/redirect
Image above: Action returns the result of a number
Image above: returns the result of the string collection
Image above: output the result of a text file
Image above: returns the result of ContentResult
Image above: the result of system exception. The output status code is 500.
Image above: throws the result of a business exception and outputs a status code of 200
After reading this, the article "how to use the ActionFilterAttribute unified interface return value format for .NetCore Web Api" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it before you can understand it. If you want to know more about related articles, welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.