在Web API中使用RedirectToAction

Thi*_*ena 6 c# redirect redirecttoaction asp.net-web-api

我在我的ASP.Net WebAPI应用程序中使用RedirectToAction,我尝试了以下一个.

return RedirectToAction("AuthenticateUser", "AuthenticationServiceWebApi", new RouteValueDictionary
                                                                    {
                                                                        {"userName", model.UserName},
                                                                        {"password", model.Password}
                                                                    });
Run Code Online (Sandbox Code Playgroud)

这将生成如下重定向.

127.0.0.1:81/authenticationservicewebapi/authenticateuser/admin/admin@123
Run Code Online (Sandbox Code Playgroud)

但是,由于我使用的是WebAPI,我需要成为下面的URL.

127.0.0.1:81/api/authenticationservicewebapi/authenticateuser/admin/admin@123
Run Code Online (Sandbox Code Playgroud)

我该怎么做呢?

Ali*_*tad 5

如果用户未通过身份验证,则不应重定向。另一端通常没有交互式用户,因此您应该真正返回 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);
Run Code Online (Sandbox Code Playgroud)


Fil*_*p W 4

我不确定你的路由、Web API 操作签名是什么样子,所以我会尝试猜测。有些事情在这里并没有真正加起来(为什么要在网址中传递密码?)

但...

考虑到你的 url 结构,我猜你的路由是这样的:

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

鉴于此,我猜您的authenticateuser 一定是这样的:

public HttpResponseMessage AuthenticateUser([FromUri]string id, [FromUri]string id2)
Run Code Online (Sandbox Code Playgroud)

如果是这样,那么要从 MVC 控制器重定向到此,您需要:

        return Redirect(
            Url.RouteUrl("DefaultApi", 
                new { httproute = "", 
                      controller = "AuthenticationServiceWebApi", 
                      action = "AuthenticateUser", 
                      id = model.UserName,
                      id2 = model.Password
            }));
Run Code Online (Sandbox Code Playgroud)

  • `RedirectToAction` 是 MVC,而不是 Web API。 (15认同)