I have the following code in my we api:

  public static void Register(HttpConfiguration config)
    {


        // Web API routes
        config.MapHttpAttributeRoutes();

        //Set default content to json
        var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
        config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);

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

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

Here is the conreoller and actionmethod I am trying to connect to:

  [Authorize]
public class DeviceConnectionController : ApiController
{        
    [HttpGet]
    public string Status(int deviceId)
    {
        string stats = "1234:";
        stats += FSK_APNLink.ConnectionStatus.Connected.ToString();
        return stats;
    }
}

Now the following get request gives me a 404:

http://localhost:50000/api/deviceconnection/status/45

however if I remove the parameter from the action method the following executes correctly:

http://localhost:50000/api/deviceconnection/status
有帮助吗?

解决方案

There is an optional parameter called id which is matched by the route against the list of method parameters. The only method parameter is called deviceId, hence it won't have any value. You either need to rename the parameter in the method signature or in the route template.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top