Query parameter routing with asp .net core

vidriduch picture vidriduch · Dec 7, 2016 · Viewed 13.5k times · Source

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.

Answer

jcmontx picture jcmontx · Dec 7, 2016

This is what you're looking for

public IActionResult GetAllTranslations([FromQuery]string languageCode)