3

Im building a simple api with asp.netcore 1.1 and trying to create hypermedia links. I have looked at

WebAPI Url.Link() returning NULL

and a couple of similars, but none of those were of help.

my controller is

[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/organizers")]
public class OrganizersController : Controller
{
    [HttpGet, Route("{id:int}", Name = "get-organizers")]
    public IActionResult Get(int id)
    {
        try
        {
            var uri = Url.Link("default", new {id=2});
            var uri2 = Url.RouteUrl("default", new { controller = "Organizers", action = "get-organizers", id = 1 });
            (...)
        }
        (...)

     }

My startup looks like

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime appLifetime)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        //serilog
        loggerFactory.AddSerilog();

        app.UseMvc(opt=>opt.MapRoute("default", "api/v{version:apiVersion}/{controller}/{action}/{id:int?}"));
        appLifetime.ApplicationStopped.Register(() => ApplicationContainer.Dispose());
    }

i have tried many permutations of the possible parameters including removing action, api, version, etc. still, i get null for both urls.

1
  • Shouldn't the action parameter be "Get" instead of the Routename? Commented Feb 9, 2017 at 15:40

2 Answers 2

3

I've tried your example and

Url.Link("default", new {id=2});

returns http://localhost:1237/api/v1.0/Organizers/Get/1 and

Url.RouteUrl("default", new {controller = "Organizers", action = "get-organizers", id = 1});

returns /api/v1.0/Organizers/get-organizers/1, even though get-organizers action is not defined, it's a route name.

However,

Url.Action("Get", new { id = id });
// or
Url.RouteUrl("get-organizers", new { id = id });

returns /api/v1.0/organizers/1, which looks more RESTful.

You should not be getting NULL values. Make sure you have API versioning enabled.

    public void ConfigureServices( IServiceCollection services )
    {
        services.AddMvc();
        services.AddApiVersioning( o => o.ReportApiVersions = true );
    }
Sign up to request clarification or add additional context in comments.

1 Comment

i hadnt versioning on.
0

You can generate a url in a couple of ways, see here for the full documentation

Please try this

With Url.Action

Url.Action("Get", "Organizers", new { id = 1 });

With a named route

Url.RouteUrl("get-organizers", new {id = 1});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.