标签: asp.net-web-api-routing

如何强制Web API识别查询字符串参数

ASP.NET MVC4 Web API v1控制器定义如下.它应该接受1或2个查询字符串参数.

但是,如果调用method,则ko参数始终为null.请求如下.如何修复以便klient或namepart参数可以在查询字符串中传递?

Web API v1控制器:

namespace MyApp.Controllers
{
    public class CustomersSearchViewModel
    {
        public string Klient { get; set; }
        public string Namepart { get; set; }
    }


    [Authorize]
    public class CustomersController : ApiController
        {

        public HttpResponseMessage Get(CustomersSearchViewModel ko)
            {
             // why ko is null ?         
             var res = GetCustomers(ko.Klient,ko.Namepart);
             return Request.CreateResponse(HttpStatusCode.OK, 
                    new { customers = res.ToArray() } );
            }

        }
    }
Run Code Online (Sandbox Code Playgroud)

Controller按请求调用(appl从erp virtal目录运行):

GET /erp/api/customers?namepart=kaks&_=1385320904347 HTTP/1.1
Host: localhost:52216
Connection: keep-alive
Accept: application/json, text/javascript, */*; q=0.01
X-Requested-With: …
Run Code Online (Sandbox Code Playgroud)

asp.net asp.net-mvc asp.net-mvc-4 asp.net-web-api asp.net-web-api-routing

13
推荐指数
1
解决办法
2万
查看次数

WebApi:将参数映射到标头值

我做了一些搜索,但似乎没有找到任何东西......

使用WebApi,我想将输入参数映射到标头值:例如

例如在控制器中:

public User GetUser(int id){
   ...
   return user;
}
Run Code Online (Sandbox Code Playgroud)

我希望WebApi将id参数映射到标头值(例如X-Auth:1234)...而不是URL参数.

这支持吗?

asp.net asp.net-web-api asp.net-web-api-routing

13
推荐指数
3
解决办法
1万
查看次数

如何将ASP.NET Web API属性路由与复杂对象参数一起使用?

我有一个Web API操作,如下所示:

[HttpGet]
[Route("api/query/hello/{query}")]
public HttpResponseMessage Hello([FromUri]Query query)
{
    return null;
}
Run Code Online (Sandbox Code Playgroud)

其中Query类具有名为的公共字符串属性QueryText.当我点击以下网址时,收到404错误:

/api/query/hello?QueryText=bacon
Run Code Online (Sandbox Code Playgroud)

这在我开始使用属性路由之前有效.如果我没有参数或基本类型参​​数,我可以使属性路由工作.但是对于复杂的参数,我得到了404s.属性路由如何使用复杂的操作参数?它与FromUri属性兼容吗?

c# asp.net-web-api asp.net-web-api-routing

13
推荐指数
1
解决办法
7066
查看次数

是否有应用于Web API ApiController方法的默认动词?

我一直在看这篇文章的代码(在https://github.com/patelsan/WebAPIAuthentication中):http://www.codeproject.com/Articles/630986/Cross-Platform-Authentication-With-ASP- NET-Web-API.

它非常好,似乎工作正常.很少有文章解释这种令牌认证,但这是我见过的最好的.请注意,我是这项技术的新手,还有很多需要学习的地方.

所以,我注意到UsersController有这样的代码:

public class UsersController : ApiController
{
    public Status Authenticate(User user)
    {
        . . .
    }
}
Run Code Online (Sandbox Code Playgroud)

Authenticate方法不是以已知的HTTP动词开头,例如Get或Post,并且没有与此方法关联的[HttpGet]或[HttpPost]属性,那么控制器如何知道哪个动词与此方法相关联?只需查看代码,我怎么知道我需要使用哪个动词?如果没有匹配的话,是否存在"默认"动词这样的事情?

顺便说一句,如果你想知道,唯一有效的动词是POST.我很想知道为什么会这样.

asp.net asp.net-web-api asp.net-web-api-routing

13
推荐指数
2
解决办法
7091
查看次数

Web Api 2.2 OData V4功能路由

我有一个使用OData v4的Web Api 2.2项目.正常的EntitySet配置可以根据需要使用所有http谓词.我遇到问题的地方是尝试公开自定义函数.我开始尝试做一些不同于标准示例的事情,但我一直支持尝试使基本示例函数正常工作.

这是我的启动配置(直接来自MS示例):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.OData.Builder;
using System.Web.OData.Extensions;

namespace Test.Service
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {

            // other entitysets that don't have functions

            builder.EntitySet<Product>("Products");
            builder.Namespace = "ProductService";
            builder.EntityType<Product>().Collection
                .Function("MostExpensive")
                .Returns<double>();

            config.MapODataServiceRoute(
                "odataroute"
                , "odata"
                , builder.GetEdmModel()                        
                );
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的控制器:

using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.OData;

namespace Test.Service.Controllers
{
    public class ProductsController : ODataController
    {
        private …
Run Code Online (Sandbox Code Playgroud)

c# odata asp.net-web-api asp.net-web-api-routing

13
推荐指数
2
解决办法
8075
查看次数

尚未使用WebApi Delegating处理程序分配内部处理程序

我在我的代码中遇到WebApi抛出异常的问题:

public class WebApiAuthenticationHandler : DelegatingHandler
    {
        private const string AuthToken = "AUTH-TOKEN";

        protected override Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request, CancellationToken cancellationToken)
        {                  
            var requestAuthTokenList = GetRequestAuthTokens(request);
            if (ValidAuthorization(requestAuthTokenList))
            {
                // EXCEPTION is occuring here!....
                return base.SendAsync(request, cancellationToken);
            }

            /*
            ** This will make the whole API protected by the API token.
            ** To only protect parts of the API then mark controllers/methods
            ** with the Authorize attribute and always return this:
            **
            ** return base.SendAsync(request, cancellationToken);
            */
            return Task<HttpResponseMessage>.Factory.StartNew(
                () …
Run Code Online (Sandbox Code Playgroud)

asp.net asp.net-web-api asp.net-web-api-routing

12
推荐指数
2
解决办法
1万
查看次数

Web API 2路由属性不起作用

我正在使用.NET 4.5的最终版本和Web API 2(在Visual Studio 2013中).我一直在使用这个文档作为参考,但无济于事.

我有几条基本路线

api/providers
api/locations
api/specialties
Run Code Online (Sandbox Code Playgroud)

并且每个方法都有类似的

Get()
Get(int id)
Get(string keyword)
Autocomplete(string keyword)
Search(string zipcode, string name, int radius, [...])
Run Code Online (Sandbox Code Playgroud)

理想情况下,我希望URL最终会像

  • / api/locations/12345(获取位置12345)
  • / api/locations/clinical(获取名称中带有"临床"的位置)
  • / api/locations/autocomplete?keyword = clinical (获取名称中带有"clinical"的位置的精简Id + Name对象)
  • / api/locations/search?zipcode = 12345&radius = 20&name = clinical (获取位于邮编12345之内20英里内的位置,名称中带有"临床")

在下面的代码块中,Get方法和Search工作按需要,但Autocomplete没有.应该注意的是,我在多个控制器中有类似的命名方法.我究竟做错了什么?(另外,Name =财产到底是什么?)

/// <summary>
/// This is the API used to interact with location information.
/// </summary>
[RoutePrefix("api/locations")]
public class LocationController : …
Run Code Online (Sandbox Code Playgroud)

c# asp.net asp.net-mvc-4 asp.net-web-api asp.net-web-api-routing

12
推荐指数
1
解决办法
9777
查看次数

使用媒体类型对ASP.NET Web API 2进行版本控制

我正在使用ASP.NET Web API 2进行属性路由,但我似乎无法使用媒体类型application/vnd.company[.version].param[+json]进行版本控制.

在此输入图像描述

我收到以下错误:

给定的密​​钥不在字典中.

从测试的关键起源_actionParameterNames[descriptor]FindActionMatchRequiredRouteAndQueryParameters()方法.

foreach (var candidate in candidatesFound)
{
        HttpActionDescriptor descriptor = candidate.ActionDescriptor;
        if (IsSubset(_actionParameterNames[descriptor], candidate.CombinedParameterNames))
        {
            matches.Add(candidate);
        }
}
Run Code Online (Sandbox Code Playgroud)

来源:ApiControllerActionSelector.cs

经过进一步调试后,我意识到如果你有两个控制器

[RoutePrefix("api/people")]
public class PeopleController : BaseApiController
{
    [Route("")]
    public HttpResponseMessage GetPeople()
    {
    }

    [Route("identifier/{id}")]
    public HttpResponseMessage GetPersonById()
    {
    }
}

[RoutePrefix("api/people")]
public class PeopleV2Controller : BaseApiController
{     
    [Route("")]
    public HttpResponseMessage GetPeople()
    {
    } 

    [Route("identifier/{id}")]
    public HttpResponseMessage GetPersonById()
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

你不能使用你的自定义,ApiVersioningSelector : DefaultHttpControllerSelector 因为它将测试所有具有相同的控制器的键,如上所述,[RoutePrefix("api/people")]显然会抛出异常. …

c# asp.net-web-api asp.net-web-api-routing

12
推荐指数
1
解决办法
5036
查看次数

将所有Web API请求路由到一个控制器方法

是否可以自定义ASP.NET Web API的路由机制,以将所有请求路由到一个控制器方法?

如果有请求进来

www.mysite.com/api/products/
Run Code Online (Sandbox Code Playgroud)

要么

www.mysite.com/api/otherResource/7
Run Code Online (Sandbox Code Playgroud)

所有这些都将被路由到我的SuperDuperController的Get()方法?

asp.net asp.net-web-api-routing asp.net-web-api2

12
推荐指数
2
解决办法
5149
查看次数

Swashbuckle设置manualy operationId

我需要知道是否可以设置自定义operationid或命名约定,我的意思是我知道操作过滤器可以覆盖如何生成operationId的方式

https://azure.microsoft.com/en-us/documentation/articles/app-service-api-dotnet-swashbuckle-customize/

using Swashbuckle.Swagger;
using System.Web.Http.Description;

namespace Something
{
    public class MultipleOperationsWithSameVerbFilter : IOperationFilter
    {
        public void Apply(
            Operation operation,
            SchemaRegistry schemaRegistry,
            ApiDescription apiDescription)
        {
            if (operation.parameters != null)
            {
                operation.operationId += "By";
                foreach (var parm in operation.parameters)
                {
                    operation.operationId += string.Format("{0}",parm.name);
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在SwaggerConfig.cs中

 c.OperationFilter<MultipleOperationsWithSameVerbFilter>();
Run Code Online (Sandbox Code Playgroud)

现在这有助于改变招摇的描述,请检查以下内容:

在此输入图像描述

一切都很好,现在我最终在一个更黑暗的地方,例如类似于可能的情况:在同一个控制器上我有两个端点

  • 发布:/ customer boddy:{email,location ....}
  • 发布:/ customer/search boddy:{a filter,whatever}

这个例子不太正确(最后一篇文章应该是get)但仍然假设webapi无法更改(新的控制器用于分离)对于这个特殊情况我会试着找出一种方法来为每个动作以某种方式生成operationId diffrent,但我的问题是:

是否有可能以某种方式装饰与[JsonIgnore]或[Route("customer/delete")]类似的控制器动作,以明确有关operationId的信息.

c# asp.net-web-api swagger asp.net-web-api-routing swashbuckle

12
推荐指数
2
解决办法
8096
查看次数