Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query parameter routing with asp .net core

I'd like to use url query parameter instead of path parameter using .net core API.

controller

[Route("api/[controller]/[action]")]
public class TranslateController : Controller
{
    [HttpGet("{languageCode}")]
    public IActionResult GetAllTranslations(string languageCode)
    {
        return languageCode;
    }
}

startup.cs is using only default settings

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc()
            .AddJsonOptions(jsonOptions =>
            {
                jsonOptions.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
                jsonOptions.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                jsonOptions.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            });

    services.AddLogging();
    services.AddSingleton<IConfiguration>(Configuration);

    services.AddSwaggerGen(c =>
    {
        c.SingleApiVersion(new Info
        {
            Version = "v1",
            Title = "Translate API",
            Description = "bla bla bla description",
            TermsOfService = "bla bla bla terms of service"
        });
    });
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    app.UseMvc();

    app.UseSwagger();
    app.UseSwaggerUi();
}

my swagger request looks like this enter image description here

my postman request is here enter image description here

I would like to change my GetAllTranslations to accept query parameter instead of path parameter but when I change my postman query to

http://localhost:42677/api/Translate/GetAllTranslations?languageCode=en

I will get error 404 Not found so obviously my controller path is not set correctly, but I cannot find out how to do this... Any Ideas?

I have tried removing the [HttpGet("{languageCode}")] attribute, but I keep getting null parameter instead of the value.

like image 339
vidriduch Avatar asked Dec 07 '16 16:12

vidriduch


People also ask

What is routing and how can you define routes in ASP.NET Core?

In ASP.NET Core MVC, this process is known as routing. Routing is the process of directing an HTTP request to a controller. Let us now understand how to route requests to different controllers. The ASP.NET Core middleware needs a way to determine if a given HTTP request should go to a controller for processing or not.

How do you handle routing in .NET Core?

Routing uses a pair of middleware, registered by UseRouting and UseEndpoints: UseRouting adds route matching to the middleware pipeline. This middleware looks at the set of endpoints defined in the app, and selects the best match based on the request. UseEndpoints adds endpoint execution to the middleware pipeline.

How do I enable routing in .NET Core?

Routing in ASP.NET Core MVC is the mechanism through which incoming requests are mapped to controllers and their actions. This is achieved by adding Routing middleware to the pipeline and using IRouteBuilder to map URL pattern (template) to a controller and action.


2 Answers

This is what you're looking for

public IActionResult GetAllTranslations([FromQuery]string languageCode)
like image 180
jcmontx Avatar answered Jan 04 '23 17:01

jcmontx


The answer from @jcmontx worked, but it doesn't explain why parameter bindind needs to be explicitly set. I am still not sure if and why is this enforced, but one reason would be that if binding parameters are not set explicitly, it opens up the API to be used the way it was not intended, which is not very secure neither a good practice.

like image 22
vidriduch Avatar answered Jan 04 '23 16:01

vidriduch