简体   繁体   English

如何解决webapi错误

[英]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 Webapi配置

 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 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 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. 您正在注册2条相同的路线,因此将执行第一个匹配项。 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} . 一种方法是将模板指定为api/apiClient/{id}

The route api/apiClient matches both of your routes. 路线api/apiClient匹配您的两条路线。 To fix it simply remove the second one, your route will match the first one and will arrive at the controller. 要解决此问题,只需删除第二条路线,您的路线将与第一个路线匹配并到达控制器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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