2

I have two methods for getting a list of projects, or an individual project. However, when I try to implement attribute routing I get a '405 Method Not Allowed' error. One method takes a string (returning a list of projects), the other an integer (returning a single project), how can I get the routing to work?

[HttpGet]
[Route("api/projects/{search}")]
public List<JsonProject> Get(string search = null)
{
}

[HttpGet]
[Route("api/projects/{id:int}")]
public JsonProject Get(int id)
{
}

The 'search' parameter is optional (by default it returns all records) and I may want to add 'sort' as well (also optional). If I take Route out I can get the list of projects, but not the individual project

global.asax has

GlobalConfiguration.Configure(WebApiConfig.Register);

and the routing

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {

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

        var json = config.Formatters.JsonFormatter;
        json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;

        config.Formatters.Remove(config.Formatters.XmlFormatter);

    }
}
1
  • Check the Allow header in your 405 Method Not Allowed response and let us know what it tells Commented Feb 7, 2014 at 15:17

1 Answer 1

3

Add another route for the search parameter. It's for when the search is null, it will work.See below:

[HttpGet]
[Route("api/projects/")]
[Route("api/projects/{search}")]
public List<JsonProject> Get(string search = null){ }

Also, try to remove the WebDav handler and WebDav module from web.config and change the ExtensionlessUrl handler verb attribute.

<system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules runAllManagedModulesForAllRequests="true">
      <remove name="WebDAVModule" />
    </modules>
    <handlers>
      <remove name="WebDAV" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT" type="System.Web.Handlers.TransferRequestHandler" resourceType="Unspecified" requireAccess="Script" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>

  </system.webServer>
Sign up to request clarification or add additional context in comments.

1 Comment

That would maybe mean I need to if else in the same action method to call different methods e.g. from a service? Isn't there something like an overloading so I don't need to use conditions?

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.