首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >路由属性不像预期的那样工作。

路由属性不像预期的那样工作。
EN

Stack Overflow用户
提问于 2017-03-05 10:09:24
回答 3查看 580关注 0票数 0

我的Web-API-2应用程序正在使用路由属性来定义路由,但它似乎不像我预期的那样工作:从后端返回错误405或404。操作方法搜索未启动(内有断点)。

我的代码、请求和响应如下:

JS代码:

代码语言:javascript
复制
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);
                        }
                    });

后端控制器代码:

代码语言:javascript
复制
//[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类:

代码语言:javascript
复制
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 }
            );
        }
    }

Global.asax.css:

代码语言:javascript
复制
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();

        }
    }

我的请求:

代码语言:javascript
复制
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

我的答复是:

代码语言:javascript
复制
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代码更改为:

代码语言:javascript
复制
 apiService.get('/api/customers/search', config, customersLoadCompleted, customersLoadFailed);

主计长:

代码语言:javascript
复制
 [HttpGet]
 [Route("search")]
 public HttpResponseMessage Get(HttpRequestMessage request, int? page, int? pageSize, string filter = null)
{

它起作用了:)。

但当控制人员有行动时:

代码语言:javascript
复制
[HttpGet]
 [Route("search")]
 public HttpResponseMessage Search(HttpRequestMessage request, int? page, int? pageSize, string filter = null)
 { 
...

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

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-03-05 14:10:21

我找到了解决办法:)我犯了一个愚蠢的错误:)我加错名字了

using System.Web.Mvc;

而不是

using System.Web.Http;

但非常奇怪的是:)。

票数 0
EN

Stack Overflow用户

发布于 2017-03-05 10:31:57

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

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

  1. 搜索
  2. {page:int=0}
  3. {pageSize=4}
  4. {过滤器?}

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

您现在有两个选择:删除页面属性之前的问号,然后将get请求更改为

代码语言:javascript
复制
[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

票数 1
EN

Stack Overflow用户

发布于 2017-03-08 05:48:56

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42607038

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档