简体   繁体   English

WebAPI 2自定义路由

[英]WebAPI 2 custom routing

I have added the custome routing to a WebAPI ASP.NET application, using framework 4.7.1, by adding the attribute on top of the method: 我已使用框架4.7.1通过在方法顶部添加属性,将自定义路由添加到WebAPI ASP.NET应用程序中:

public class ShapeFileAnalysisController : ApiController
{
    [HttpGet]
    [Route("GetDataValues")]
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    public HttpResponseMessage GetDataValues()
    {
        string result = Models.ShapeFileReader.GetAdmin2();
        HttpResponseMessage response = this.Request.CreateResponse(HttpStatusCode.OK);
        response.Content = new StringContent(result, Encoding.UTF8, "application/json");
        return response;
    }  
}

but when I add [Route("...")} attribute the full URL changes from mysite.com/api/ShapeFileAnalysis to mysite.com/GetDataValues 但是当我添加[Route(“ ...”)}属性时,完整的URL将从mysite.com/api/ShapeFileAnalysis更改为mysite.com/GetDataValues

the webapiconfig.cs is: webapiconfig.cs是:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        config.EnableCors();

        // Web API routes
        config.MapHttpAttributeRoutes();

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

What I should do to have still mysite.com/api/ShapeFileAnalysis/GetDataValues ? 我应该怎么做才能仍然拥有mysite.com/api/ShapeFileAnalysis/GetDataValues?

It's posible that you are mixing two ways to implement a WebApi in Net framework as is mention on the Microsoft Documentation - https://docs.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/routing-and-action-selection . 正如您在Microsoft文档中提到的,您可能会混合使用两种方法在Net框架中实现WebApi- https ://docs.microsoft.com/zh-cn/aspnet/web-api/overview/web-api-routing 和动作/路由和动作选择

In the first one (the one that you are follow) the routing matching is throught the parameter of the verbs (GET, POST, PUT, DELETE), this means that when you do a Get you distinguish between method using the parameter's name (examples are aviable in Microsoft's Documentation mentioned before). 在第一个(您所遵循的)中,路由匹配是通过动词的参数(GET,POST,PUT,DELETE)进行的,这意味着在执行Get时,您会使用参数的名称来区分方法(示例在前面提到的Microsoft文档中可用)。

In the second one you can Add a Route and controller route on the top to tell the compiler in which route it should to expose the method. 在第二个中,您可以在顶部添加一个Route和controller路由,以告诉编译器应该在哪个路由中公开该方法。

I didn't have the time to test in VS my suggestion but I believe that you need to add one more attribute - RoutePrefixAttribute . 我没有时间测试VS的建议,但我相信您需要再添加一个属性-RoutePrefixAttribute
Your code should be be following: 您的代码应如下:

[RoutePrefix( "api/ShapeFileAnalysis" )]    //  new line of code!
public class ShapeFileAnalysisController : ApiController
{
    [HttpGet]
    [Route("GetDataValues")]
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    public HttpResponseMessage GetDataValues()
    {

    }  
}

Attribute routing uses the route template placed in the attribute. 属性路由使用放置在属性中的路由模板。

Your route has only GetDataValues so that will become the full route path. 您的路线只有GetDataValues因此它将成为完整的路线路径。

mysite.com/GetDataValues

If you place the desired route path 如果放置所需的路径

//GET api/ShapeFileAnalysis/GetDataValues
[HttpGet]
[Route("api/ShapeFileAnalysis/GetDataValues")]
[EnableCors(origins: "*", headers: "*", methods: "*")]
public HttpResponseMessage GetDataValues() {
    //...
} 

Then you will get the desired path 然后,您将获得所需的路径

mysite.com/api/ShapeFileAnalysis/GetDataValues

You can set a common prefix for an entire controller by using the [RoutePrefix] attribute 您可以使用[RoutePrefix]属性为整个控制器设置通用前缀

[RoutePrefix( "api/ShapeFileAnalysis" )] 
public class ShapeFileAnalysisController : ApiController {

    //GET api/ShapeFileAnalysis/GetDataValues
    [HttpGet]
    [Route("GetDataValues")]
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    public HttpResponseMessage GetDataValues() {
        //...omitted for brevity
    }  
}

Reference Attribute Routing in ASP.NET Web API 2 ASP.NET Web API 2中的参考属性路由

For this situation "mysite.com/api/ShapeFileAnalysis/GetDataValues" If all requests will be in this template. 对于这种情况,如果所有请求都在此模板中,则为“ mysite.com/api/ShapeFileAnalysis/GetDataValues”。 You don't have to use Custom Route . 您不必使用自定义路线

The other answer is the solution of the problem, but I want to offer a different alternative. 另一个答案是解决问题的方法,但是我想提供另一种选择。 Change default route and remove all route attributes . 更改默认路由删除所有路由属性 Route Template add action tag. 路线模板添加操作标签。

Example: 例:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        config.EnableCors();

        // Web API routes
        config.MapHttpAttributeRoutes();

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

Referance: Routing in ASP.NET Web API 参考: ASP.NET Web API中的路由

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM