2017-03-05 145 views
0

我的Web-API-2应用程序使用Route属性来定义路由,但它看起来不像我预期的那样工作:从后端返回错误405或404。 操作方法搜索没有开始(里面有断点)。路由属性不能正常工作

我的代码,请求和响应以下:

JS代码:

var url ='/api/customers/search/', 
var config = { 
       params: { 
        page: 0, 
        pageSize: 4, 
        filter: $scope.filterCustomers 
       } 
      }; 
$http.get(url, config).then(function (result) { 
         success(result); 
        }, function (error) { 
         if (error.status == '401') { 
          notificationService.displayError('Authentication required.'); 
          $rootScope.previousState = $location.path(); 
          $location.path('/login'); 
         } 
         else if (failure != null) { 
          failure(error); 
         } 
        }); 

后端控制器的代码:

//[Authorize(Roles = "Admin")] 
[RoutePrefix("api/customers")] 
public class CustomersController : ApiControllerBase 
{ 
    private readonly IEntityBaseRepository<Customer> _customersRepository; 

    public CustomersController(IEntityBaseRepository<Customer> customersRepository, 
     IEntityBaseRepository<Error> _errorsRepository, IUnitOfWork _unitOfWork) 
     : base(_errorsRepository, _unitOfWork) 
    { 
     _customersRepository = customersRepository; 
    } 


    //[Route("search/?{page:int=0}&{pageSize=4}")] 
    [Route("search/?{page:int=0}/{pageSize=4}/{filter?}")] 
    [HttpGet] 
    public HttpResponseMessage Search(HttpRequestMessage request, int? page, int? pageSize, string filter = null) 
    { 
     int currentPage = page.Value; 
     int currentPageSize = pageSize.Value; 
... 

类WebApiConfig:

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

      //use authetication handler 
      config.MessageHandlers.Add(new HomeCinemaAuthHandler()); 

      // Enable Route attributes 
      config.MapHttpAttributeRoutes(); 

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

全球。一个sax.css:

public class Global : HttpApplication 
    { 
     void Application_Start(object sender, EventArgs e) 
     { 

      var config = GlobalConfiguration.Configuration; 

      AreaRegistration.RegisterAllAreas(); 

      //Use web api routes 
      WebApiConfig.Register(config); 

      //Autofac, Automapper, ... 
      Bootstrapper.Run(); 

      //Use mvc routes 
      RouteConfig.RegisterRoutes(RouteTable.Routes); 



      //register bundles 
      BundleConfig.RegisterBundles(BundleTable.Bundles); 

      GlobalConfiguration.Configuration.EnsureInitialized(); 

     } 
    } 

我的要求:

GET http://localhost:65386/api/customers/search/?page=0&pageSize=4 HTTP/1.1 
Accept: application/json, text/plain, */* 
Referer: http://localhost:65386/ 
Accept-Language: pl-PL 
Accept-Encoding: gzip, deflate 
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko 
Host: localhost:65386 
Connection: Keep-Alive 

我的回答是:

HTTP/1.1 405 Method Not Allowed 
Cache-Control: no-cache 
Pragma: no-cache 
Allow: POST 
Content-Type: application/json; charset=utf-8 
Expires: -1 
Server: Microsoft-IIS/10.0 
X-AspNet-Version: 4.0.30319 
X-SourceFiles: =?UTF-8?B?QzpcIXdvcmtcVmlkZW9SZW50YWxcSG9tZUNpbmVtYS5XZWJcYXBpXGN1c3RvbWVyc1xzZWFyY2hc?= 
X-Powered-By: ASP.NET 
Date: Sun, 05 Mar 2017 09:47:27 GMT 
Content-Length: 72 

{"Message":"The requested resource does not support http method 'GET'."} 

=================== ====

更新1:

我改变JS代码:

apiService.get('/api/customers/search', config, customersLoadCompleted, customersLoadFailed); 

和控制器:

[HttpGet] 
[Route("search")] 
public HttpResponseMessage Get(HttpRequestMessage request, int? page, int? pageSize, string filter = null) 
{ 

和它的作品:)。

但是,当控制器有动作:

[HttpGet] 
[Route("search")] 
public HttpResponseMessage Search(HttpRequestMessage request, int? page, int? pageSize, string filter = null) 
{ 
... 

错误仍然错误405不允许的方法。为什么?

回答

0

我找到了解决方案:)我是我愚蠢的错误:)。我加错了名字空间

using System.Web.Mvc;

,而不是

using System.Web.Http;

它的工作,但很奇怪的:)。

1

您的//localhost:65386/api/customers/search/?page=0&pageSize=4获取请求与您的路由配置不符。

[Route("search/?{page:int=0}/{pageSize=4}/{filter?}")]定义4路由属性:

  1. 搜索
  2. ?:{ε滤波器} {页INT = 0}
  3. {的pageSize = 4}

这导致你的第一个错误:你混合querystrings和路由配置。如果你想使用querystrings,只需使用它们。它们不属于路线属性。 这会使您的路由配置无效。

你有两个选择现在:页面属性之前删除问号和改变你的GET请求

[Route("search/{page:int=0}/{pageSize=4}/{filter?}")] 
//localhost:65386/api/customers/search/0/4/optional-filter-value 

或删除您的路由数据的注释,并用普通的查询字符串的工作://localhost:65386/api/customers/search?page=0&pageSize=4&filter=something

+0

嗯,奇怪,但仍然是相同的问题... –

+0

几乎作品,我添加更新1到我的文章。 –

0

基本提示! System.Web.Http一个用于Web API; System.Web.Mvc一个是以前的MVC版本。 MVC是Web应用程序,Web API是HTTP服务。