在控制器中使用两个参数进行操作-如何设置路径和控制器?

时间:2019-09-21 17:13:14

标签: vb.net http get asp.net-web-api2 asp.net-web-api-routing

我有这个控制器:

 Public Class UsersController
    Inherits ApiController
    Public reportsjsonfilepath = System.AppDomain.CurrentDomain.BaseDirectory & "\reports.json"
    <HttpGet>
    <Route("")>
    Public Function Index() As HttpResponseMessage
        Log.Information("Main index requested at {0}", DateTime.Now)
        Dim response As StringBuilder = New StringBuilder
        response.Append("Index requested at: " & DateTime.Now)
        response.Append("<br>")
        response.Append("Hello, this is a test WebApi server!")
        Dim raspuns = String.Join("/n", response.ToString)
        Dim raspunsindex = Request.CreateResponse(Of String)(HttpStatusCode.OK, raspuns)
        raspunsindex.Content.Headers.ContentType = New MediaTypeHeaderValue("text/html")
        Return raspunsindex
    End Function
    <HttpGet>
    <Route("users")>
    Public Function Users() As HttpResponseMessage
        Log.Information("Users index requested at {0}", DateTime.Now)
        Dim response As StringBuilder = New StringBuilder()
        Dim dictionarusers As IDictionary(Of String, String) = GetUsersList()
        Dim i As Integer = 0
        For Each entry As KeyValuePair(Of String, String) In dictionarusers
            i = i + 1
            response.Append(i)
            response.Append(" - ")
            response.Append(entry.Value)
            response.Append("<br>")
        Next
        Dim raspuns = Request.CreateResponse(Of String)(HttpStatusCode.OK, response.ToString)
        raspuns.Content.Headers.ContentType = New MediaTypeHeaderValue("text/html")
        Return raspuns
    End Function
    <HttpGet>
    Public Function GetQlikLink(username As String, reportId As Integer) As HttpResponseMessage
        QlikLink.GetLink(username, reportId)
    End Function
End Class

路线设置如下:

    Public Module RoutesConfig
            <Extension()>
            Sub MapDefinedRoutes(ByVal config As HttpConfiguration)
                config.Routes.MapHttpRoute(name:="Relevance", routeTemplate:="api/{controller}", defaults:=New With {
                    .id = RouteParameter.[Optional]
                })
                config.Routes.MapHttpRoute("QlikLink", "api/{controller}/{action}/{id}", New With {
    .id = RouteParameter.[Optional]
}) 

    End Sub
    End Module

现在,当我进入http://localhost:9000/relevance时,索引会显示OK。与http://localhost:9000/relevance/users相同。但是,如何必须通过从请求中获取参数来设置动作和路线以获得某些东西呢?如何发送参数:?username = somestring&?id = 2?我说的是功能GetQlikLink,是Controller中的最后一个。

任何提示将不胜感激!非常感谢!

1 个答案:

答案 0 :(得分:0)

对于参数与路由配置中定义的参数不同的操作,则查询字符串键应与功能参数名称相同。

http://..../GetQlikLink?username=xyz&reportId=1234

我建议阅读有关路由的不同类型的信息。
您显示的配置类似于基于约定的路由。
但是,您似乎也在向操作方法添加路由属性。

基于公约的路由允许您定义路由模板,并且{controller}{action}之类的模式必须与控制器和操作的名称匹配。

Routing and Action Selection in ASP.NET Web API

本节中的其他文章还介绍了属性路由。