简体   繁体   中英

ASP.NET Core - Exception filter attribute how to build URL like Url.Action

I have a .NET Core attribute for handling expcetions:

    public class ExceptionActionAttribute : ExceptionFilterAttribute
            {
         public override void OnException(ExceptionContext context)
                {
        
        .... some code 
        
// this is how you do it in .NET 4 MVC
        var exceptionUrl = Url.Action("Test", "Error", new { errorId = errorUid.ToString() });
        
        }
    
    }

I would like to build the Url just like in .NET 4 using Url.Action, is there a way or how is the right way to build it so I can get the right path as in my example.

Read up LinkGenerator Class .

Defines a contract to generate absolute and related URIs based on endpoint routing.

You can resolve that within the filter and generate links using the current request's HttpContext

public class ExceptionActionAttribute : ExceptionFilterAttribute {
    public override void OnException(ExceptionContext context) {
    
        // .... some code 
    
        // resolve LinkGenerater
        LinkGenerater linkGenerater  = context.HttpContext.RequestServices.GetService<LinkGenerater>()

        // and use it to generate URLs
        var exceptionUrl = linkGenerater.GetUriByAction(context.HttpContext, 
            action: "Test",
            controller: "Error",
            values: new { FileId = 1 }
        );

        //...
    
    }    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM