WebApi 重定向 Redirect 注意重定向的方法 method 要使用GET,其他的试过都报错 Http 405
有时候在api执行完一个方法后,我们还得再跳到另外一个方法执行其他操作。
这种情况下,我们可以调用方法,也可以根据情况进行重定向作业
private void button2_Click(object sender, EventArgs e) { HttpWebRequest request=(HttpWebRequest) WebRequest.Create("http://localhost:20137/api/Demo?Name=张三&Gender=M&age=22"); request.Method = "GET"; //通过URL传值的话,可以不指定 contentType //request.ContentType = "text/html;charset=utf-8"; //request.ContentType = "application/x-www-form-urlencoded;charset=utf-8"; using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { string result = reader.ReadToEnd(); this.textBox1.Text = result; } } }
第一种 Redirect
public IHttpActionResult Get([FromUri]Person person) { return Redirect("http://localhost:20137/api/Demo/TestRedirect?name=张三");// 这种可以,不过action返回类型是IHttpActionResult //return Content<Person>(HttpStatusCode.BadRequest,person); } [HttpGet] [Route("api/Demo/TestRedirect")] public IHttpActionResult TestRedirect([FromUri]string name) { return Json("成功跳转"+ name); }
推荐
[Route("action1")] [HttpGet] public IHttpActionResult Action1() { Console.WriteLine("Action1"); return new RedirectResult(new Uri("http://localhost:3721/api/demo/action2"), this); } [Route("action2")] [HttpGet] public IHttpActionResult Action2() { Console.WriteLine("Action2"); return new RedirectResult(new Uri("http://localhost:3721/api/demo/action3"), this); } [Route("action3")] [HttpGet] public IHttpActionResult Action3() { return new OkResult(this); }
第二种 利用HttpReponseMessage
public HttpResponseMessage Get([FromUri]Person person) { var response = Request.CreateResponse(HttpStatusCode.Moved); response.Headers.Location = new Uri("http://localhost:20137/api/Demo/TestRedirect?name=张三"); response.Content = new ObjectContent(typeof(string), "重定向传值", new JsonMediaTypeFormatter()); return response;// 这种也可以,不过action 返回类型是 HttpResponseMessage } [HttpGet] [Route("api/Demo/TestRedirect")] public IHttpActionResult TestRedirect([FromUri]string name) { return Json("成功跳转"+ name); }