RoutePrefix different than Controller name doesn't work











up vote
0
down vote

favorite












In my WebApiConfig.cs file I have :



public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services

// Web API routes
config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);

var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
}


I have a OrderController



[RoutePrefix("api/Orders")]
public class OrderController : ApiController
{
[Authorize]
[Route("")]
public IHttpActionResult Get()
{
return Ok(Order.CreateOrders());
}


As expected, the above code works with url - http://localhost:15660/api/Orders



I got another CustomerController :



[Authorize]
[RoutePrefix("api/Customers")]
public class CustomerController : ApiController
{
// GET api/customers/search
[HttpGet]
[Route("search/{location}/{customerName}/{phoneNumber}/{email}")]
public IHttpActionResult SearchCustomers(string location = null, string customerName = null, string phoneNumber = null, string email = null)
{
return Ok(GetCustomersSearchResults(location, customerName, phoneNumber, email));
}


Here, I want to call as /api/Customers/search - but this gives error for no match controller name found. If I rename the prefix to



[RoutePrefix("api/Customer")]


then it works perfectly well.



In Ordercontroller, api/Orders works perfectly well. In CustomerController, why api/customersdoesn't work at all and gives error. I googled a lot, found the syntax is correct, but can't figure where am I going wrong that is restricting CustomerController to map with /api/Customers/search



Can anyone please help me know how to map CustomerController the way I want to using [RoutePrefix].



Thanks a lot.










share|improve this question


























    up vote
    0
    down vote

    favorite












    In my WebApiConfig.cs file I have :



    public static class WebApiConfig
    {
    public static void Register(HttpConfiguration config)
    {
    // Web API configuration and services

    // Web API routes
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
    );

    var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
    jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    }
    }


    I have a OrderController



    [RoutePrefix("api/Orders")]
    public class OrderController : ApiController
    {
    [Authorize]
    [Route("")]
    public IHttpActionResult Get()
    {
    return Ok(Order.CreateOrders());
    }


    As expected, the above code works with url - http://localhost:15660/api/Orders



    I got another CustomerController :



    [Authorize]
    [RoutePrefix("api/Customers")]
    public class CustomerController : ApiController
    {
    // GET api/customers/search
    [HttpGet]
    [Route("search/{location}/{customerName}/{phoneNumber}/{email}")]
    public IHttpActionResult SearchCustomers(string location = null, string customerName = null, string phoneNumber = null, string email = null)
    {
    return Ok(GetCustomersSearchResults(location, customerName, phoneNumber, email));
    }


    Here, I want to call as /api/Customers/search - but this gives error for no match controller name found. If I rename the prefix to



    [RoutePrefix("api/Customer")]


    then it works perfectly well.



    In Ordercontroller, api/Orders works perfectly well. In CustomerController, why api/customersdoesn't work at all and gives error. I googled a lot, found the syntax is correct, but can't figure where am I going wrong that is restricting CustomerController to map with /api/Customers/search



    Can anyone please help me know how to map CustomerController the way I want to using [RoutePrefix].



    Thanks a lot.










    share|improve this question
























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      In my WebApiConfig.cs file I have :



      public static class WebApiConfig
      {
      public static void Register(HttpConfiguration config)
      {
      // Web API configuration and services

      // Web API routes
      config.MapHttpAttributeRoutes();

      config.Routes.MapHttpRoute(
      name: "DefaultApi",
      routeTemplate: "api/{controller}/{id}",
      defaults: new { id = RouteParameter.Optional }
      );

      var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
      jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
      }
      }


      I have a OrderController



      [RoutePrefix("api/Orders")]
      public class OrderController : ApiController
      {
      [Authorize]
      [Route("")]
      public IHttpActionResult Get()
      {
      return Ok(Order.CreateOrders());
      }


      As expected, the above code works with url - http://localhost:15660/api/Orders



      I got another CustomerController :



      [Authorize]
      [RoutePrefix("api/Customers")]
      public class CustomerController : ApiController
      {
      // GET api/customers/search
      [HttpGet]
      [Route("search/{location}/{customerName}/{phoneNumber}/{email}")]
      public IHttpActionResult SearchCustomers(string location = null, string customerName = null, string phoneNumber = null, string email = null)
      {
      return Ok(GetCustomersSearchResults(location, customerName, phoneNumber, email));
      }


      Here, I want to call as /api/Customers/search - but this gives error for no match controller name found. If I rename the prefix to



      [RoutePrefix("api/Customer")]


      then it works perfectly well.



      In Ordercontroller, api/Orders works perfectly well. In CustomerController, why api/customersdoesn't work at all and gives error. I googled a lot, found the syntax is correct, but can't figure where am I going wrong that is restricting CustomerController to map with /api/Customers/search



      Can anyone please help me know how to map CustomerController the way I want to using [RoutePrefix].



      Thanks a lot.










      share|improve this question













      In my WebApiConfig.cs file I have :



      public static class WebApiConfig
      {
      public static void Register(HttpConfiguration config)
      {
      // Web API configuration and services

      // Web API routes
      config.MapHttpAttributeRoutes();

      config.Routes.MapHttpRoute(
      name: "DefaultApi",
      routeTemplate: "api/{controller}/{id}",
      defaults: new { id = RouteParameter.Optional }
      );

      var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
      jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
      }
      }


      I have a OrderController



      [RoutePrefix("api/Orders")]
      public class OrderController : ApiController
      {
      [Authorize]
      [Route("")]
      public IHttpActionResult Get()
      {
      return Ok(Order.CreateOrders());
      }


      As expected, the above code works with url - http://localhost:15660/api/Orders



      I got another CustomerController :



      [Authorize]
      [RoutePrefix("api/Customers")]
      public class CustomerController : ApiController
      {
      // GET api/customers/search
      [HttpGet]
      [Route("search/{location}/{customerName}/{phoneNumber}/{email}")]
      public IHttpActionResult SearchCustomers(string location = null, string customerName = null, string phoneNumber = null, string email = null)
      {
      return Ok(GetCustomersSearchResults(location, customerName, phoneNumber, email));
      }


      Here, I want to call as /api/Customers/search - but this gives error for no match controller name found. If I rename the prefix to



      [RoutePrefix("api/Customer")]


      then it works perfectly well.



      In Ordercontroller, api/Orders works perfectly well. In CustomerController, why api/customersdoesn't work at all and gives error. I googled a lot, found the syntax is correct, but can't figure where am I going wrong that is restricting CustomerController to map with /api/Customers/search



      Can anyone please help me know how to map CustomerController the way I want to using [RoutePrefix].



      Thanks a lot.







      c# asp.net-web-api2






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 11 at 4:14









      Terry

      2917




      2917
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          4
          down vote



          accepted










          The issue is not that the RoutePrefix is different from your controller name (you could set RoutePrefix("abcdefg") if you wanted), but that you have specified location, customerName, phoneNumber and email as required paths in your URL so only a URL such as this would work in your current setup: /api/Customers/search/EU/cust1/1234/email.



          What you probably want is a query string, not values in your URL. For example: /api/Customers/search?location=EU&customerName=cust1&phoneNumber=123. So simply change your route to [Route("search")] and such a URL will work!



          Tring to pass multiple optional values in through the URL just won't work, what if you pass a URL such as api/Customers/search/value. How will the server know if value is supposed to be location or customerName?



          Here's a question regarding URL parameters and query strings: What is the difference between URL parameters and query strings?






          share|improve this answer





















          • thanks for your response. URL with NO or Any # or All parameters is working on the above code. With the code, /api/Customers/search gives error for no matching controller name. /api/Customer/search works perfectly. how to make /api/Customers/search work.
            – Terry
            Nov 12 at 16:37












          • @TruptiDalia I am not able to reproduce... when I change to [RoutePrefix("api/Customer")] it gives me No action was found on the controller 'Customer' that matches the request.. Regardless, my point is that you should not be using the URL to pass parameters anyways.
            – obl
            Nov 12 at 17:00










          • hmm, strange. When I use api/Customers it produces error and is fine with api/customer. Reg URL params, I read the link you shared; couldn't get what I should do to implement in this code. I think you are asking to remove params from the [Route]. I had tried adding in function params as SearchCustomers(string? location = null, string? customerName = null, string? phoneNumber = null, string? email = null). Adding ? to string gives error (as string is non-nullable object). I tried with just string? location, but no success. Can you guide what should I do to implement the same.
            – Terry
            Nov 12 at 17:09










          • No need to change any code other than the route, read the 2nd paragraph in my answer
            – obl
            Nov 12 at 17:12










          • @ obl, Thank you for this correction.
            – Terry
            Nov 12 at 22:28











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














           

          draft saved


          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53245778%2frouteprefix-different-than-controller-name-doesnt-work%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          4
          down vote



          accepted










          The issue is not that the RoutePrefix is different from your controller name (you could set RoutePrefix("abcdefg") if you wanted), but that you have specified location, customerName, phoneNumber and email as required paths in your URL so only a URL such as this would work in your current setup: /api/Customers/search/EU/cust1/1234/email.



          What you probably want is a query string, not values in your URL. For example: /api/Customers/search?location=EU&customerName=cust1&phoneNumber=123. So simply change your route to [Route("search")] and such a URL will work!



          Tring to pass multiple optional values in through the URL just won't work, what if you pass a URL such as api/Customers/search/value. How will the server know if value is supposed to be location or customerName?



          Here's a question regarding URL parameters and query strings: What is the difference between URL parameters and query strings?






          share|improve this answer





















          • thanks for your response. URL with NO or Any # or All parameters is working on the above code. With the code, /api/Customers/search gives error for no matching controller name. /api/Customer/search works perfectly. how to make /api/Customers/search work.
            – Terry
            Nov 12 at 16:37












          • @TruptiDalia I am not able to reproduce... when I change to [RoutePrefix("api/Customer")] it gives me No action was found on the controller 'Customer' that matches the request.. Regardless, my point is that you should not be using the URL to pass parameters anyways.
            – obl
            Nov 12 at 17:00










          • hmm, strange. When I use api/Customers it produces error and is fine with api/customer. Reg URL params, I read the link you shared; couldn't get what I should do to implement in this code. I think you are asking to remove params from the [Route]. I had tried adding in function params as SearchCustomers(string? location = null, string? customerName = null, string? phoneNumber = null, string? email = null). Adding ? to string gives error (as string is non-nullable object). I tried with just string? location, but no success. Can you guide what should I do to implement the same.
            – Terry
            Nov 12 at 17:09










          • No need to change any code other than the route, read the 2nd paragraph in my answer
            – obl
            Nov 12 at 17:12










          • @ obl, Thank you for this correction.
            – Terry
            Nov 12 at 22:28















          up vote
          4
          down vote



          accepted










          The issue is not that the RoutePrefix is different from your controller name (you could set RoutePrefix("abcdefg") if you wanted), but that you have specified location, customerName, phoneNumber and email as required paths in your URL so only a URL such as this would work in your current setup: /api/Customers/search/EU/cust1/1234/email.



          What you probably want is a query string, not values in your URL. For example: /api/Customers/search?location=EU&customerName=cust1&phoneNumber=123. So simply change your route to [Route("search")] and such a URL will work!



          Tring to pass multiple optional values in through the URL just won't work, what if you pass a URL such as api/Customers/search/value. How will the server know if value is supposed to be location or customerName?



          Here's a question regarding URL parameters and query strings: What is the difference between URL parameters and query strings?






          share|improve this answer





















          • thanks for your response. URL with NO or Any # or All parameters is working on the above code. With the code, /api/Customers/search gives error for no matching controller name. /api/Customer/search works perfectly. how to make /api/Customers/search work.
            – Terry
            Nov 12 at 16:37












          • @TruptiDalia I am not able to reproduce... when I change to [RoutePrefix("api/Customer")] it gives me No action was found on the controller 'Customer' that matches the request.. Regardless, my point is that you should not be using the URL to pass parameters anyways.
            – obl
            Nov 12 at 17:00










          • hmm, strange. When I use api/Customers it produces error and is fine with api/customer. Reg URL params, I read the link you shared; couldn't get what I should do to implement in this code. I think you are asking to remove params from the [Route]. I had tried adding in function params as SearchCustomers(string? location = null, string? customerName = null, string? phoneNumber = null, string? email = null). Adding ? to string gives error (as string is non-nullable object). I tried with just string? location, but no success. Can you guide what should I do to implement the same.
            – Terry
            Nov 12 at 17:09










          • No need to change any code other than the route, read the 2nd paragraph in my answer
            – obl
            Nov 12 at 17:12










          • @ obl, Thank you for this correction.
            – Terry
            Nov 12 at 22:28













          up vote
          4
          down vote



          accepted







          up vote
          4
          down vote



          accepted






          The issue is not that the RoutePrefix is different from your controller name (you could set RoutePrefix("abcdefg") if you wanted), but that you have specified location, customerName, phoneNumber and email as required paths in your URL so only a URL such as this would work in your current setup: /api/Customers/search/EU/cust1/1234/email.



          What you probably want is a query string, not values in your URL. For example: /api/Customers/search?location=EU&customerName=cust1&phoneNumber=123. So simply change your route to [Route("search")] and such a URL will work!



          Tring to pass multiple optional values in through the URL just won't work, what if you pass a URL such as api/Customers/search/value. How will the server know if value is supposed to be location or customerName?



          Here's a question regarding URL parameters and query strings: What is the difference between URL parameters and query strings?






          share|improve this answer












          The issue is not that the RoutePrefix is different from your controller name (you could set RoutePrefix("abcdefg") if you wanted), but that you have specified location, customerName, phoneNumber and email as required paths in your URL so only a URL such as this would work in your current setup: /api/Customers/search/EU/cust1/1234/email.



          What you probably want is a query string, not values in your URL. For example: /api/Customers/search?location=EU&customerName=cust1&phoneNumber=123. So simply change your route to [Route("search")] and such a URL will work!



          Tring to pass multiple optional values in through the URL just won't work, what if you pass a URL such as api/Customers/search/value. How will the server know if value is supposed to be location or customerName?



          Here's a question regarding URL parameters and query strings: What is the difference between URL parameters and query strings?







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 11 at 4:59









          obl

          1,424629




          1,424629












          • thanks for your response. URL with NO or Any # or All parameters is working on the above code. With the code, /api/Customers/search gives error for no matching controller name. /api/Customer/search works perfectly. how to make /api/Customers/search work.
            – Terry
            Nov 12 at 16:37












          • @TruptiDalia I am not able to reproduce... when I change to [RoutePrefix("api/Customer")] it gives me No action was found on the controller 'Customer' that matches the request.. Regardless, my point is that you should not be using the URL to pass parameters anyways.
            – obl
            Nov 12 at 17:00










          • hmm, strange. When I use api/Customers it produces error and is fine with api/customer. Reg URL params, I read the link you shared; couldn't get what I should do to implement in this code. I think you are asking to remove params from the [Route]. I had tried adding in function params as SearchCustomers(string? location = null, string? customerName = null, string? phoneNumber = null, string? email = null). Adding ? to string gives error (as string is non-nullable object). I tried with just string? location, but no success. Can you guide what should I do to implement the same.
            – Terry
            Nov 12 at 17:09










          • No need to change any code other than the route, read the 2nd paragraph in my answer
            – obl
            Nov 12 at 17:12










          • @ obl, Thank you for this correction.
            – Terry
            Nov 12 at 22:28


















          • thanks for your response. URL with NO or Any # or All parameters is working on the above code. With the code, /api/Customers/search gives error for no matching controller name. /api/Customer/search works perfectly. how to make /api/Customers/search work.
            – Terry
            Nov 12 at 16:37












          • @TruptiDalia I am not able to reproduce... when I change to [RoutePrefix("api/Customer")] it gives me No action was found on the controller 'Customer' that matches the request.. Regardless, my point is that you should not be using the URL to pass parameters anyways.
            – obl
            Nov 12 at 17:00










          • hmm, strange. When I use api/Customers it produces error and is fine with api/customer. Reg URL params, I read the link you shared; couldn't get what I should do to implement in this code. I think you are asking to remove params from the [Route]. I had tried adding in function params as SearchCustomers(string? location = null, string? customerName = null, string? phoneNumber = null, string? email = null). Adding ? to string gives error (as string is non-nullable object). I tried with just string? location, but no success. Can you guide what should I do to implement the same.
            – Terry
            Nov 12 at 17:09










          • No need to change any code other than the route, read the 2nd paragraph in my answer
            – obl
            Nov 12 at 17:12










          • @ obl, Thank you for this correction.
            – Terry
            Nov 12 at 22:28
















          thanks for your response. URL with NO or Any # or All parameters is working on the above code. With the code, /api/Customers/search gives error for no matching controller name. /api/Customer/search works perfectly. how to make /api/Customers/search work.
          – Terry
          Nov 12 at 16:37






          thanks for your response. URL with NO or Any # or All parameters is working on the above code. With the code, /api/Customers/search gives error for no matching controller name. /api/Customer/search works perfectly. how to make /api/Customers/search work.
          – Terry
          Nov 12 at 16:37














          @TruptiDalia I am not able to reproduce... when I change to [RoutePrefix("api/Customer")] it gives me No action was found on the controller 'Customer' that matches the request.. Regardless, my point is that you should not be using the URL to pass parameters anyways.
          – obl
          Nov 12 at 17:00




          @TruptiDalia I am not able to reproduce... when I change to [RoutePrefix("api/Customer")] it gives me No action was found on the controller 'Customer' that matches the request.. Regardless, my point is that you should not be using the URL to pass parameters anyways.
          – obl
          Nov 12 at 17:00












          hmm, strange. When I use api/Customers it produces error and is fine with api/customer. Reg URL params, I read the link you shared; couldn't get what I should do to implement in this code. I think you are asking to remove params from the [Route]. I had tried adding in function params as SearchCustomers(string? location = null, string? customerName = null, string? phoneNumber = null, string? email = null). Adding ? to string gives error (as string is non-nullable object). I tried with just string? location, but no success. Can you guide what should I do to implement the same.
          – Terry
          Nov 12 at 17:09




          hmm, strange. When I use api/Customers it produces error and is fine with api/customer. Reg URL params, I read the link you shared; couldn't get what I should do to implement in this code. I think you are asking to remove params from the [Route]. I had tried adding in function params as SearchCustomers(string? location = null, string? customerName = null, string? phoneNumber = null, string? email = null). Adding ? to string gives error (as string is non-nullable object). I tried with just string? location, but no success. Can you guide what should I do to implement the same.
          – Terry
          Nov 12 at 17:09












          No need to change any code other than the route, read the 2nd paragraph in my answer
          – obl
          Nov 12 at 17:12




          No need to change any code other than the route, read the 2nd paragraph in my answer
          – obl
          Nov 12 at 17:12












          @ obl, Thank you for this correction.
          – Terry
          Nov 12 at 22:28




          @ obl, Thank you for this correction.
          – Terry
          Nov 12 at 22:28


















           

          draft saved


          draft discarded



















































           


          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53245778%2frouteprefix-different-than-controller-name-doesnt-work%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Bressuire

          Vorschmack

          Quarantine