[英]How to change already assigned route in ASP.NET web api 2
请指出正确的问题,如果这是重复的。 我还没有找到可以解决我所表达内容的方法。
所以我有一个具有两条相同路线的控制器
// 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)
唯一的区别是HTTP方法。 现在当我使用路线时,第二条路线称为
// PUT: api/UserPwordHints/5
我的WebConfig.cs看起来像这样
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
这是默认值。 通过对SO的搜索,我知道我添加了一个代码,该代码明确指示要使用的代码。 但是,它们都有相同的路线。 分辨使用哪种确切方法的最佳方法是什么?
编辑:使用GET方法仍会调用PUT方法并出现错误
cannot send a content-body with this verb-type post
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
为这两种方法定义的路由相同,但是方法的类型不同无需更改默认路由。
如果要调用GetUserPwordHintsModels()
,请使用route作为
// GET: api/UserPwordHints/5
^^^^ See the difference
如果要调用PutUserPwordHintsModels()
,请使用route作为
// PUT: api/UserPwordHints/5
^^^^ PUT and GET
您可以使用HTTPPut
和HTTPGet
批注装饰方法。 如同
// 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)
有关更多详细信息: MSDN路由到控制器操作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.