简体   繁体   中英

How do I generate a url inside a c# service?

Really simple I hope. I just want to do the equivalent of

Url.Action("SomeAction", "SomeController", new { id = 3 });

But inside a service class. Not inside a controller class or IActionResult method

In a plain old service class. Because of the service call having all the data I don't want to pass in other information so my service call is nice and clean.

I've come close but nothing seems to work, either that or it cant be done.

I tried to dependency inject this

services.AddScoped<IUrlHelper>(x => x
            .GetRequiredService<IUrlHelperFactory>()
            .GetUrlHelper(x.GetRequiredService<IActionContextAccessor>().ActionContext));

In my service call I used (DI) this

public AdminService(..., IUrlHelper urlHelper)

so in my service method I could to this

string editUrl = _urlHelper.Action("EditRole", "Admin", new { id = 0 });

which got rid of all the red squiglies but at run time this bit caused me a problem

            .GetUrlHelper(x.GetRequiredService<IActionContextAccessor>().ActionContext));

You can inject IUrlHelper interface inside a service class.

public class ServiceClass
    {
        private readonly IActionContextAccessor _actionContextAccessor;
        private readonly IUrlHelperFactory _urlHelperFactory;

        public ServiceClass(IActionContextAccessor actionContextAccessor,
            IUrlHelperFactory urlHelperFactory,)
        {
            _actionContextAccessor = actionContextAccessor;
            _urlHelperFactory = urlHelperFactory;
        }

        public string CreateUrl()
        {
            var urlHelper = _urlHelperFactory.GetUrlHelper(_actionContextAccessor.ActionContext);
            string url = urlHelper.Action("SomeAction", "SomeController");

            return url;
        }
    }

@SMM I had to add this to my startup but otherwise, works, so thank you

services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
services.AddSingleton<IUrlHelper, UrlHelper>();

Url.Action generates only an url. @Url.Action("actionName", "controllerName", new { id = id })

Html.ActionLink generates an tag automatically.

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