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

ASP.NET Web API中带有可选参数的属性路由

我正在尝试使用Web API 2属性路由来设置自定义API.我的路由工作,我的函数被调用,但由于某种原因,我需要传入我的第一个参数,以便一切正常工作.以下是我要支持的网址:

http://mysite/api/servicename/parameter1
http://mysite/api/servicename/parameter1?parameter2=value2
http://mysite/api/servicename/parameter1?parameter2=value2&parameter3=value3
http://mysite/api/servicename/parameter1?parameter2=value2&parameter3=value3&p4=v4
Run Code Online (Sandbox Code Playgroud)

最后3个URL可以工作,但第一个说"在控制器名称上没有找到与请求相匹配的操作".

我的控制器看起来像这样:

public class MyServiceController : ApiController
{
    [Route("api/servicename/{parameter1}")]
    [HttpGet]
    public async Task<ReturnType> Get(string parameter1, DateTime? parameter2, string parameter3 = "", string p4 = "")
    {
        // process
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

CreatedAtRoute路由到不同的控制器

我正在使用属性路由创建一个新的webapi来创建嵌套路由,如下所示:

    // PUT: api/Channels/5/Messages
    [ResponseType(typeof(void))]
    [Route("api/channels/{id}/messages")]
    public async Task<IHttpActionResult> PostChannelMessage(int id, Message message)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        if (id != message.ChannelId)
        {
            return BadRequest();
        }

        db.Messages.Add(message);
        await db.SaveChangesAsync();

        return CreatedAtRoute("DefaultApi", new { id = message.Id }, message);
    }
Run Code Online (Sandbox Code Playgroud)

但是我想返回一个没有嵌套的路由,即:

/api/Messages/{id}
Run Code Online (Sandbox Code Playgroud)

这是在消息控制器上定义的.但是,上面的CreatedAtRoute调用不解析此路线而是抛出.我做错了什么,或者它不支持路由到不同的api控制器?我试图点击的路线不是属性路线,只是默认路线.

例外是:

消息:"发生了错误." ExceptionMessage:"UrlHelper.Link不能返回null." ExceptionType:"System.InvalidOperationException"StackTrace:"at System.Web.Http.Results.CreatedAtRouteNegotiatedContentResult 1.Execute() at System.Web.Http.Results.CreatedAtRouteNegotiatedContentResult1.ExecuteAsync(CancellationToken cancellationToken)at System.Web.Http.Controllers.ApiControllerActionInvoker.d__0.MoveNext()---堆栈跟踪结束从抛出异常的上一个位置---在System.Runtime.Compiler服务的System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务),System.Runtime.CompilerServices.TaskAwaiter的System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)1.GetResult() at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter1.GetResult( …

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

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

Web API路由约束HttpMethod中缺少补丁

我正在使用.net Web API V1构建一些restful api.

我们正在尝试为web api定义一些路由.我在定义'Put'和'patch'的路线时遇到了一些问题.

它们具有相同的URL,唯一不同的是HttpMethod.在HttpMethod中,没有对Patch的支持http://msdn.microsoft.com/en-us/library/system.net.http.httpmethod(v=vs.118).aspx

config.Routes.MapHttpRoute(
    "UpdateCustomer",
    "api/customers/id/{id}",
    new {controller = "Customers", action = "UpdateCustomer"},
    new {id = @"\d+", httpMethod = new HttpMethodConstraint(HttpMethod.Put)}
);

config.Routes.MapHttpRoute(
    "PatchCustomer",
    "api/customers/id/{id}",
     new {controller = "Customers", action = "PatchCustomer"},
     new {id = @"\d+", httpMethod = new HttpMethodConstraint(HttpMethod.**Patch**)}
);
Run Code Online (Sandbox Code Playgroud)

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

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

在URL中使用斜杠"/"路由参数

我知道您可以在route属性中应用通配符以允许/例如日期输入:

[Route("orders/{*orderdate}")]
Run Code Online (Sandbox Code Playgroud)

通配符的问题仅适用于URI中的最后一个参数.如果要拥有以下URI,如何解决问题:

[Route("orders/{orderdate}/customers")]
Run Code Online (Sandbox Code Playgroud)

更新:

我知道通过重构代码来解决问题的选择很少,所以请不要提供类似的解决方案:

  1. 将路径模板更改为 [Route("orders/customers/{orderdate}")]
  2. 将日期更改为其他格式(例如"dd-mm-yyyy")

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

35
推荐指数
2
解决办法
3万
查看次数

asp.net webapi 2属性路由无法正常工作

我使用.net framework 4.5安装了使用mvc4的visual studio 2012.现在我想使用带有属性编写的webapi2,我希望我的hlep页面能够正确显示所有端点.

在我的解决方案中,我添加了一个新的mvc4基础emtpy项目并使用nuget i升级到mvc5,然后我安装了webapi2软件包.最后我已经为webapi2安装了帮助包.

现在,当我使用routeprefix时,我无法在帮助页面上看到任何内容,当我尝试在浏览器中访问我的webapi端点时,它会抛出以下错误.

http://expressiis.com/api/v1/

   <Error>
    <Message>
    No HTTP resource was found that matches the request URI 'http://expressiis.com/api/v1/'.
    </Message>
    <MessageDetail>
    No type was found that matches the controller named 'v1'.
    </MessageDetail>
    </Error>

namespace WebApi.Controllers
{
    [RoutePrefix("api/v1")]
    public class SubscribersController : ApiController
    {
        // GET api/<controller>   
        [Route("")]
        [HttpGet]
        public IQueryable<string> Get()
        {
            return new string[] { "value1", "value2" }.AsQueryable();
        }


    }
}
Run Code Online (Sandbox Code Playgroud)

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

33
推荐指数
5
解决办法
4万
查看次数

FromBody字符串参数给出null

这可能是非常基本的东西,但我无法弄清楚我哪里出错了.

我试图从POST的主体中获取一个字符串,但"jsonString"只显示为null.我也想避免使用模型,但也许这是不可能的.我用PostMan打的那段代码是这个块:

[Route("Edit/Test")]
[HttpPost]
public void Test(int id, [FromBody] string jsonString)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

也许这是我对邮递员做错的事情,但我一直试图在身体的价值部分使用"= test"(如在关于这个主题的其他问题中看到的那样) - x-www-form-urlencoded section with密钥作为jsonString而没有.我也尝试过使用raw-text和raw-text/plain.我得到了身份证,所以我知道网址是正确的.任何有关这方面的帮助将不胜感激.

PostMan目前设置如下:

POST http://localhost:8000/Edit/Test?id=111
key = id  value = 111
Body - x-www-form-urlencoded
key = jsonString  value = "=test"
Run Code Online (Sandbox Code Playgroud)

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

30
推荐指数
9
解决办法
8万
查看次数

基于查询字符串参数名称的路由

我正在尝试在我的MVC4 WebAPI项目中配置路由.

我希望能够根据他们的名字或类型搜索产品,如下所示:

/api/products?name=WidgetX- 返回名为WidgetX的所有产品 /api/products?type=gadget- 返回gadget类型的所有产品

路由配置如下:

config.Routes.MapHttpRoute(
    name: "Get by name",
    routeTemplate: "api/products/{name}",
    defaults: new { controller = "ProductSearchApi", action = "GetProductsByName", name = string.Empty }
);

config.Routes.MapHttpRoute(
    name: "Get by type",
    routeTemplate: "api/products/{type}",
    defaults: new { controller = "ProductSearchApi", action = "GetProductsByType", type = string.Empty }
);
Run Code Online (Sandbox Code Playgroud)

问题是查询字符串参数的名称似乎被忽略,因此第一个路径始终是使用的路径,无论查询字符串参数的名称如何.如何修改我的路线以使其正确?

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

25
推荐指数
2
解决办法
4万
查看次数

具有多个参数的Web API路由

我正在尝试找出如何为以下Web API控制器进行路由:

public class MyController : ApiController
{
    // POST api/MyController/GetAllRows/userName/tableName
    [HttpPost]
    public List<MyRows> GetAllRows(string userName, string tableName)
    {
        ...
    }

    // POST api/MyController/GetRowsOfType/userName/tableName/rowType
    [HttpPost]
    public List<MyRows> GetRowsOfType(string userName, string tableName, string rowType)
    {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

目前,我正在使用此路由到URL:

routes.MapHttpRoute("AllRows", "api/{controller}/{action}/{userName}/{tableName}",
                    new
                    {
                        userName= UrlParameter.Optional,
                        tableName = UrlParameter.Optional
                    });

routes.MapHttpRoute("RowsByType", "api/{controller}/{action}/{userName}/{tableName}/{rowType}",
                    new
                    {
                        userName= UrlParameter.Optional,
                        tableName = UrlParameter.Optional,
                        rowType= UrlParameter.Optional
                    });
Run Code Online (Sandbox Code Playgroud)

但目前只有第一种方法(有2个参数)正在工作.我是在正确的路线上,还是我的URL格式或路由完全错误?路由对我来说似乎是黑魔法......

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

25
推荐指数
2
解决办法
8万
查看次数

Swagger 2.0不支持:带路径的多个操作

我在WebApi 2应用程序中集成了swagger.应用程序有单个控制器时,它工作正常.当我在应用程序中添加第二个控制器时.我收到以下错误:

发生错误.","ExceptionMessage":"Swagger 2.0不支持:路径'api/Credential'和方法'GET'的多个操作.请参阅配置设置 - \"ResolveConflictingActions \"以获取潜在的解决方法","ExceptionType":"System.NotSupportedException","StackTrace":"at Swashbuckle.Swagger.SwaggerGeneratorOptions.DefaultConflictingActionsResolver(IEnumerable 1 apiDescriptions)\r\n at Swashbuckle.Swagger.SwaggerGenerator.CreatePathItem(IEnumerable1 apiDescriptions,SchemaRegistry schemaRegistry)\ r \在Swashbuckle.Swagger.SwaggerGenerator.<> c__DisplayClass7.b__4(IGrouping 2 group)\r\n at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable1 source,Func 2 keySelector, Func2 elementSelector,IEqualityComparer 1 comparer)\r\n at Swashbuckle.Swagger.SwaggerGenerator.GetSwagger(String rootUrl, String apiVersion)\r\n at Swashbuckle.Application.SwaggerDocsHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\r\n at System.Net.Http.HttpMessageInvoker.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\r\n at System.Web.Http.Dispatcher.HttpRoutingDispatcher.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\r\n at System.Net.Http.DelegatingHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\r\n at System.Web.Http.Cors.CorsMessageHandler.<SendAsync>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.HttpServer.d__0.MoveNext()"} http:// …

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

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

控制器上的多个路由

想知道是否有可能有多个路由指向WebApi控制器?

例如,我想同时将http:// domain/calculatehttp:// domain/v2/calculate指向同一个控制器函数?

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

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