C# 路由属性未按预期工作

C# 路由属性未按预期工作,c#,asp.net-web-api2,C#,Asp.net Web Api2,我的Web-API-2应用程序正在使用Route属性来定义路由,但它似乎不像我预期的那样工作:从后端返回错误405或404。 操作方法搜索未启动(内部有断点) 我的代码、请求和响应如下: JS代码: var url ='/api/customers/search/', var config = { params: { page: 0, pageSize: 4,

我的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;
...
Global.asax.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方法不允许。为什么?

您对
//localhost:65386/api/customers/search/?page=0&pageSize=4的get请求与您的路由配置不匹配

[路由(“搜索/?{page:int=0}/{pageSize=4}/{filter?}”)]
定义4个路由属性:

  • 搜寻
  • ?{page:int=0}
  • {pageSize=4}
  • {过滤器?}
  • 这将导致您的第一个错误:您混合了查询字符串和路由配置。如果您想使用querystring,只需使用它们。它们不属于路由属性。 这会使路由配置无效

    您现在有2个选择:删除页面属性前的问号,并将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

    我找到了解决方案:)我犯了一个愚蠢的错误:)。我添加了错误的名称空间

    使用System.Web.Mvc

    而不是

    使用System.Web.Http


    它起作用了,但很奇怪:)。

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

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