WebApi 重定向 Redirect

有时候在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);
        }

  

第二种 利用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);
        }

  

上一篇:WebApi 参数验证,参数绑定后进行验证


下一篇:WebApi 通过ModelBinder绑定自定义参数对象