简体   繁体   中英

How to solve a webapi error

I cannot figure out why I am getting this error. It is a new project and i am using the same setup as my previous projects. If someone can point out what is not correct.

Error Message

    $id: "1"
     Message: "No HTTP resource was found that matches the request URI 'http://localhost:55596  /api/apiClient'."
    MessageDetail: "No type was found that matches the controller named 'apiClient'."

Webapi config

 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 }
        );
        config.Routes.MapHttpRoute(
           name: "ClientApi",
           routeTemplate: "api/{controller}/{id}",
           defaults: new { controller = "apiClient", id = RouteParameter.Optional }
       );
    }

app.js

'use strict';
 var app = angular.module('YoungIntel', [
 'ngResource',
 'ngRoute',
 'ui.bootstrap'
 ])
app.factory('Client', function ($resource) {
return $resource('/api/apiClient/:id',
  { id: '@id' },
  { 'save': { method: 'POST' } },
  { 'update': { method: 'PUT' } },
  { 'query': { method: 'GET'}});
 });
 app.factory('ClientGet', function ($http, $q) {
   return {
    query: function () {
        var deferred = $q.defer();
        $http({ method: 'get', url: '/api/apiClient' })
                .success(function (data) {
                    deferred.resolve(data);
                }).error(function (error) {
                    deferred.reject(error);
                });
        return deferred.promise;
    }
    }
 });

Controller

//GET Clients
$scope.clientArray = {};
ClientGet.query().then(function (data) { $scope.clientArray = data; }, function (reason) { errorMngrSvc.handleError(reason); });

apiController

  public class apiClientController : ApiController
  {
    IClient _adapter;

    public apiClientController()
    {
        _adapter = new ClientDataAdapter();
    }
    public apiClientController(IClient adapter)
    {
        _adapter = adapter;
    }

    // GET api/<controller>
    public IHttpActionResult Get()
    {
        var model = _adapter.GetClients();

        return Ok(model);
    }

    // GET api/<controller>/5
    public IHttpActionResult Get(int id)
    {
        Client client = new Client();
        client = _adapter.GetClient(id);
        if (client == null)
        {
            return NotFound();
        }
        return Ok(client);

    }

    // POST api/<controller>

    public IHttpActionResult PostnewClient([FromBody]Client newClient)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        var client = _adapter.PostNewClient(newClient);
        return CreatedAtRoute("ClientApi", new { newClient.ClientId }, newClient);
    }

    // PUT api/<controller>/5


    public HttpResponseMessage PutNewClient(int id, Client newClient)
    {
        ApplicationDbContext db = new ApplicationDbContext();
        if (!ModelState.IsValid)
        {
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
        }

        if (id != newClient.ClientId)
        {
            return Request.CreateResponse(HttpStatusCode.BadRequest);
        }

        db.Entry(newClient).State = EntityState.Modified;

        try
        {
            db.SaveChanges();
        }
        catch (DbUpdateConcurrencyException ex)
        {
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
        }

        return Request.CreateResponse(HttpStatusCode.OK);
    }

    // DELETE api/<controller>/5
    public IHttpActionResult DeleteClient(int id)
    {

        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        return Ok(_adapter.DeleteClient(id));
    }
}

Update

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

        // Web API routes
        config.MapHttpAttributeRoutes();

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

    }

Still getting the same error

The order of routes matter. You're registering 2 identical routes so the first match executes. Switch it to:

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

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

However, now your first route will catch everything. To avoid that, you need to change it to be different than the default route. One way is to specify the template as api/apiClient/{id} .

The route api/apiClient matches both of your routes. To fix it simply remove the second one, your route will match the first one and will arrive at the controller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM