简体   繁体   English

如何在ASP.NET Web API 2中更改已分配的路由

[英]How to change already assigned route in ASP.NET web api 2

Please point me to right question if this is a duplicate. 请指出正确的问题,如果这是重复的。 I haven't quite found one that addresses what I expressing. 我还没有找到可以解决我所表达内容的方法。

So I have a controller that has two same routes 所以我有一个具有两条相同路线的控制器

// GET: api/UserPwordHints/5
[ResponseType(typeof(UserPwordHintsModels))]
public async Task<IHttpActionResult> GetUserPwordHintsModels(string id)

// PUT: api/UserPwordHints/5
[ResponseType(typeof(void))]
public async Task<IHttpActionResult> PutUserPwordHintsModels(string id, 
UserPwordHintsModels userPwordHintsModels)

The only difference is the HTTP Method. 唯一的区别是HTTP方法。 Now when I use the route, the second route is called 现在当我使用路线时,第二条路线称为

  // PUT: api/UserPwordHints/5

My WebConfig.cs looks like this 我的WebConfig.cs看起来像这样

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

Which is the default. 这是默认值。 I know through my search on SO that I have add a code that explicitly directs which one to use. 通过对SO的搜索,我知道我添加了一个代码,该代码明确指示要使用的代码。 However they both have the same route. 但是,它们都有相同的路线。 What would be best way to tell which exact one to use? 分辨使用哪种确切方法的最佳方法是什么?

EDIT: Using a GET Method still calls the PUT Method with an Error 编辑:使用GET方法仍会调用PUT方法并出现错误

cannot send a content-body with this verb-type post

EDIT2 Calling Method EDIT2调用方法

GET_METHOD = "GET"
SendWebRequest(getPassWordHintURL, requestBody:=body, httpMethod:=GET_METHOD)


Private Function SendWebRequest(
                   requestUrl As String,
                   Optional requestBody As String = Nothing,
                   Optional httpMethod As String = "POST",
                   Optional bearerToken As String = Nothing) As String

        Dim responseFromServer

        httpReq = WebRequest.Create(requestUrl)
        httpReq.Proxy = Nothing
        httpReq.Method = httpMethod
        httpReq.ContentType = "application/json"

        If bearerToken IsNot Nothing Then
            httpReq.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + bearerToken)
        End If

        httpReq.ContentLength = 0

        If requestBody IsNot Nothing Then
            Dim dataBytes = Encoding.UTF8.GetBytes(requestBody)
            httpReq.ContentLength = dataBytes.Length
            Dim stream = httpReq.GetRequestStream()
            stream.Write(dataBytes, 0, dataBytes.Length)
            stream.Close()
        End If

        Dim resp As WebResponse
        Try
            resp = httpReq.GetResponse()
            Dim dataStream = resp.GetResponseStream()
            Dim reader = New StreamReader(dataStream)
            ' Read the content.
            responseFromServer = reader.ReadToEnd()

            dataStream.Close()
        Catch ex As WebException
            Throw ex
        End Try

        Return responseFromServer
    End Function

Routes defined for both the methods are same, but type of method is different No need to change default route. 为这两种方法定义的路由相同,但是方法的类型不同无需更改默认路由。

If you want to call GetUserPwordHintsModels() , then use route as 如果要调用GetUserPwordHintsModels() ,请使用route作为

   // GET: api/UserPwordHints/5
       ^^^^ See the difference

If you want to call PutUserPwordHintsModels() , then use route as 如果要调用PutUserPwordHintsModels() ,请使用route作为

 // PUT: api/UserPwordHints/5
    ^^^^ PUT and GET

You can decorate your methods using HTTPPut and HTTPGet annotations. 您可以使用HTTPPutHTTPGet批注装饰方法。 Similar to 如同

// GET: api/UserPwordHints/5
[ResponseType(typeof(UserPwordHintsModels)), HTTPGet]
public async Task<IHttpActionResult> GetUserPwordHintsModels(string id)

// PUT: api/UserPwordHints/5
[ResponseType(typeof(void)), HTTPPut]
public async Task<IHttpActionResult> PutUserPwordHintsModels(string id, 
UserPwordHintsModels userPwordHintsModels)

For more details : MSDN Routing to controller actions 有关更多详细信息: MSDN路由到控制器操作

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

相关问题 如何在Asp.Net Web Api中正确设置路径路径 - How to set route path correctly in Asp.Net Web Api ASP.NET Web API 2 中的路由别名 - Route Aliases in ASP.NET Web API 2 如何通过仅允许在 asp.net 核心 web Z8A35DA52ED1057271 的 Model 中分配的属性来验证请求正文 - How to Validate Request Body by allowing only attributes assigned in the Model of an asp.net core web api app 如何更改ASP.NET调用REST Web API的方式 - How to change the way REST Web API is called for ASP.NET 路由属性中的正则表达式-RESTful API ASP.NET Web API - Regex in Route attribute - RESTful API ASP.NET Web API 如何引用已经在 API 级别声明的 Object? (asp.net web-api) - How to reference Object that it has been already declared at the API level? (asp.net web-api) .NET 6 - 如何使用可选路由参数 ASP.NET 核心 WEB ZDB974238714CA8DE634A7CE1D083A - .NET 6 - How to use Optional Route Parameters ASP.NET Core WEB API? ASP.NET Web API属性路由:带有路由参数的RoutePrefix - ASP.NET Web API Attribute Routing: RoutePrefix with Route Parameter 从ASP.NET WEB API调用角路由 - Call an Angular Route from ASP.NET WEB API 在ASP.NET Web Api中以编程方式创建GET路由 - Programmatically create GET route in ASP.NET Web Api
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM