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

在Asp.NET WebApi中路由类似文件的名称

是否可以在ASP.NET Web API路由配置中添加允许处理看起来有点像文件名的URL的路由?

我尝试添加以下条目WebApiConfig.Register(),但这不起作用(使用URI api/foo/0de7ebfa-3a55-456a-bfb9-b658165df5f8/bar.group.json):

config.Routes.MapHttpRoute(
  name: "ContextGroupFile",
  routeTemplate: "api/foo/{id}/{filetag}.group.json",
  defaults: new { controller = "foo", action = "getgroup"}
  );
Run Code Online (Sandbox Code Playgroud)

以下确实有效(FooController.GetGroup(id,filetag)按预期调用)(使用URI api/foo/0de7ebfa-3a55-456a-bfb9-b658165df5f8/group/bar):

config.Routes.MapHttpRoute(
  name: "ContextGroupFile",
  routeTemplate: "api/foo/{id}/group/{filetag}",
  defaults: new { controller = "foo", action = "getgroup"}
  );
Run Code Online (Sandbox Code Playgroud)

失败的情况会返回一个IIS错误(404 - 找不到文件),看起来它是由我的应用程序之外的东西创建的.错误页面(由IIS Express生成)包含以下错误详细信息:

Module = IIS Web Core
Notification = MapRequestHandler
Handler = StaticFile
Error Code = 0x80070002
Run Code Online (Sandbox Code Playgroud)

我想这意味着一个名为"StaticFile Handler"的东西在它到达我的代码之前就已经得到了请求.最大的问题是:有没有办法防止这种情况发生?

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

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

UriPathExtensionMapping控制WebAPI中的响应格式

我在使用ASP.NET WebAPI中的UriPathExtensionMapping时遇到问题.我的设置如下:

我的路线是:

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

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

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

我的全局ASAX文件是:

    AreaRegistration.RegisterAllAreas();

    WebApiConfig.Register(GlobalConfiguration.Configuration);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
Run Code Online (Sandbox Code Playgroud)

我的控制器是:

public IEnumerable<string> Get()
{
    return new string[] { "Box", "Rectangle" };
}

// GET /api/values/5
public string Get(int id)
{
    return "Box";
}

// POST /api/values
public void …
Run Code Online (Sandbox Code Playgroud)

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

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

WebAPI如何指定将到达控制器的路由

我一直在尝试使用MVC WebAPI,非常酷的东西.但我正在努力解决路线问题.

作为一个例子,我有一个webAPI项目结构,如下所示:

项目:

  • 控制器
    • 顾客
      • CustomerController.cs
      • CustomerAddressController.cs
    • 制品
      • ProductCategoriesController.cs
      • 的ProductsController

目前我在WebApiConfig.cs中定义了一个API路由

        config.Routes.MapHttpRoute(
            name: "CustomerApi",
            routeTemplate: "api/customer/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
Run Code Online (Sandbox Code Playgroud)

当我只有客户相关的控制器时,这工作正常.所以我可以打电话:

  • GET api/customer/CustomerAddress /?customerID = 1234

但是现在我已经添加了与配置相关的产品相关控制器(当然)以获得我必须调用Uri的产品:

  • GET api/customer/products /?prodID = 5678*但我不想要这个Uri

相反,我想:

  • 获取api/products /?prodID = 5678

对于产品类别,我想要类似于:

  • 获取api /产品/类别/?catID = 1357

我认为我必须做的就是添加更多路线,但是我无法找到如何将各种控制器与我希望的路线联系起来?

如果我确实添加了另一条路线,我最终会将两条不同的uri路由到我建立的每个控制器.

如何实现我想要的逻辑分区?

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

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

Asp.net Web API属性路由404错误

我无法弄清楚为什么我的属性路由不起作用.

这是我的设置:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Attribute routing
        config.MapHttpAttributeRoutes();

        // Convention-based routing
        config.Routes.MapHttpRoute(
            name: "API Default",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的控制器与我的路由属性:

[Route("api/v1.0/orders")]
public class OrdersV1Controller
{

    [APIAuthentication(RequireAuthentication = true)]
    [HttpGet]
    [Route("{id:int}")]
    public GetOrderResponse GetOrder(int id)
    { 
      .....
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的全局asax文件:

public class Global : HttpApplication
{
    void Application_Start(object sender, EventArgs e)
    {
        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Populate;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我正在测试的URL返回404未找到:

http://localhost:60105/api/v1.0/orders/111111

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

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

在基本控制器上使用WebApi RoutePrefix属性

我希望所有继承的控制器都AdminBaseApiController以'admin'为前缀.

这当然很好:

[RoutePrefix("admin")]
public class ToggleController : AdminBaseApiController
{
    [Route("toggle")]
    public HttpResponseMessage Get()
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

然而,当我移动RoutePrefix("admin")了的ToggleController进入AdminBaseApiController(我想要它) -这条路线失败,我得到一个404.

我看这一切都错了吗?提前致谢!

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

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

元数据与WebAPi OData属性路由不起作用

我正在为OData端点使用OData属性路由.这是我的一个例子:

[ODataRoutePrefix("Profile")]
public class ProfileODataController : ODataController
{
    [ODataRoute]
    [EnableQuery]
    public IHttpActionResult Get()
    {
        var repo = new Repositories.ProfileRepository();

        return Ok(repo.GetProfiles());
    }

    [ODataRoute("({key})")]
    [EnableQuery]
    public IHttpActionResult Get([FromODataUri] string key)
    {
        var repo = new Repositories.ProfileRepository();

        var result = repo.GetProfiles().SingleOrDefault(x => x.Id== key);
        if (result == null) return NotFound();

        return Ok(result);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的设置:

config.MapODataServiceRoute("odata", "odata", ModelGenerator.GetEdmModel());
Run Code Online (Sandbox Code Playgroud)

这是我的EdmModel代:

public static IEdmModel GenerateEdmModel()
{
    var builder = new ODataConventionModelBuilder();

    builder.EntitySet<Profile>("Profile").EntityType.HasKey(x => x.Id);

    return builder.GetEdmModel();
}
Run Code Online (Sandbox Code Playgroud)

网址 /odata/Profile/odata/Profile('someid')两者都有效,但是当我尝试访问$ metadata endpoint( …

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

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

如何设置ASP.NET Web Api路由约束HTTP状态返回码

我正在使用ASP.NET Web Api 2框架并使用如下的基本路由约束.

    [Route("Number/{id:int:min(2):max(10)}")]
    public HttpResponseMessage GetNumber([FromUri] int id)
    {
        return (id > 0)
            ? Request.CreateResponse(HttpStatusCode.OK, id)
            : Request.CreateResponse(HttpStatusCode.PreconditionFailed);
    }
Run Code Online (Sandbox Code Playgroud)

我想知道当id与上面的约束,.eg 1或11冲突时,如何覆盖默认的HTTP Status Return代码404?

非常感谢.

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

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

属性路由识别可选的查询字符串参数

我有一个API动作:

 [HttpGet, Route("{id}/overview/")]
 public async Task<HttpResponseMessage> Overview(string id, DateTime from, DateTime? to)
{
...
}
Run Code Online (Sandbox Code Playgroud)

正如您所注意到的,to是可选参数,但是当我发出请求时:

"/api/cream/3d7dd454c00b/overview?from=2016-09-04T18:00:00.000Z

我收到404错误.如果我to从参数中删除: public async Task<HttpResponseMessage> Overview(string id, DateTime from)

一切正常.如何强制它与to参数一起工作?

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

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

如何使用Route属性将查询字符串与Web API绑定?

我试图让这个工作:

[Route("api/Default")]
public class DefaultController : ApiController
{
    [HttpGet, Route("{name}")]
    public string Get(string name)
    {
        return $"Hello " + name;
    }
}
Run Code Online (Sandbox Code Playgroud)

通过调用此http://localhost:55539/api/Default?name=rami但不工作,尝试了这个:http://localhost:55539/api/Default/Hello?name=rami,这也不起作用:http://localhost:55539/api/Default/Hello/rami

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

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

API路由:带路径的多个操作

我正在尝试配置我的API路由,我似乎无法绕过Swagger的这个错误:

500:{"消息":"发生错误.","ExceptionMessage":"Swagger 2.0不支持:路径'api/Doors/{OrganizationSys}'和方法'GET'的多个操作.

我明白为什么我得到错误,但我不知道如何解决它.以下是API端点:

public IHttpActionResult Get(int organizationSys)
{
    ....
}

public IHttpActionResult Get(int organizationSys, int id)
{
    ....
}


public IHttpActionResult Post([FromBody]Doors door)
{
    ....
}

public IHttpActionResult Put([FromBody]Doors door)
{
    ....
}

public IHttpActionResult Delete(int organizationSys, int id)
{
    ....
}
Run Code Online (Sandbox Code Playgroud)

这是我的路线,显然不正确:

config.Routes.MapHttpRoute(
    name: "route1",
    routeTemplate: "api/{controller}/{organizationSys}"
);

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

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}"
);
Run Code Online (Sandbox Code Playgroud)

更新:

我现在有这个,但得到同样的错误:

config.Routes.MapHttpRoute(
    name: "route1",
    routeTemplate: "api/{controller}/{organizationSys}/{id}"
);

config.Routes.MapHttpRoute(
    name: "route2", …
Run Code Online (Sandbox Code Playgroud)

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

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