2012-07-31 71 views
5

我在我的ASP.Net WebAPI應用程序中使用RedirectToAction,並嘗試了下面的一種。在Web API中使用RedirectToAction

return RedirectToAction("AuthenticateUser", "AuthenticationServiceWebApi", new RouteValueDictionary 
                    { 
                     {"userName", model.UserName}, 
                     {"password", model.Password} 
                    }); 

這將生成如下的重定向。

127.0.0.1:81/authenticationservicewebapi/authenticateuser/admin/[email protected] 

但是,因爲我使用的是WebAPI,所以我需要像下面這樣的URL。

127.0.0.1:81/api/authenticationservicewebapi/authenticateuser/admin/[email protected] 

我該怎麼做?

回答

3

我不知道你的路由,網絡API動作簽名看起來怎麼樣,所以我會嘗試猜測。 有幾件事情真的不加起來這裏(?爲什麼你會在url中傳遞密碼)

但是......

鑑於你的URL結構我猜你的路由是一樣的東西:

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

然後因爲,我猜你的authenticateUser必須是這樣的:

public HttpResponseMessage AuthenticateUser([FromUri]string id, [FromUri]string id2) 

如果是這樣,那麼從你網元上MVC控制器重定向到該編輯:

 return Redirect(
      Url.RouteUrl("DefaultApi", 
       new { httproute = "", 
         controller = "AuthenticationServiceWebApi", 
         action = "AuthenticateUser", 
         id = model.UserName, 
         id2 = model.Password 
      })); 
+12

'RedirectToAction'是MVC而不是Web API。 – Aliostad 2012-07-31 10:35:46

+0

是的,你可以通過使用重定向來解決這個問題,該方法接受一個字符串,並通過UrlHelper構建Web Api路由URL。不漂亮,但我不確定OP想要達到什麼目的。 – 2012-07-31 10:39:21

+0

工作得很好,非常感謝。 – thilok 2012-07-31 10:48:17

4

如果用戶未通過身份驗證,則不應該重定向。通常在另一端沒有交互式用戶,所以你應該真的返回HTTP狀態碼401而不是重定向。


在ASP.NET Web API中沒有等價物。

如果你堅持做那麼這就是:

你把HttpResponseException

var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.Found); 
httpResponseMessage.Headers.Location = new Uri(myAddress, UriKind.Relative); 
throw new HttpResponseException(httpResponseMessage); 
+0

我想你沒有得到它。我想要的是使用這種方法觸發Web API操作。 – thilok 2012-07-31 09:48:50

+0

@thilok我也懷疑你明白我的意思。但無論如何,如果你堅持這樣做的話,這裏是一個更新。 – Aliostad 2012-07-31 10:28:28

0

我也想出了一個簡單的解決方案。不如以上那麼好,但值得分享。

 string post_data = "userName=th&[email protected]"; 

     string uri = "http://127.0.0.1:81/api/authenticationservicewebapi/authenticateuser"; 

     // create a request 
     HttpWebRequest request = (HttpWebRequest) 
     WebRequest.Create(uri); 
     request.KeepAlive = false; 
     request.ProtocolVersion = HttpVersion.Version10; 
     request.Method = "POST"; 

     // turn our request string into a byte stream 
     byte[] postBytes = Encoding.ASCII.GetBytes(post_data); 

     // this is important - make sure you specify type this way 
     request.ContentType = "application/x-www-form-urlencoded"; 
     request.ContentLength = postBytes.Length; 
     Stream requestStream = request.GetRequestStream(); 

     // now send it 
     requestStream.Write(postBytes, 0, postBytes.Length); 
     requestStream.Close(); 

謝謝大家。