ASP.NET Web API的几点疑惑

Web API跟MVC相比较少了View模块,纯粹的数据传输交互,特别适合做API (Rest)。

两者跟传统Webform相比,最大的区别在于路由,模板执行原理不同。

MVC还是可以使用Request.QueryString, Request.Form等获取参数。不用View如果做API用?

Web API中不能使用Request.QueryString, Request.Form等获取参数,获取参数只能定义在Controller中action方法的形参中。

 

public string Get(int id,string name)
{
     return id + "," + name;
}

请求 api ?id=xx&name=xxx,可以多参数,但至少要有这两个参数。否则报错路由不匹配。

 

Post方法一样,也可按上述定义,但调用时参数必须放到URL里,不能放body,这个很不科学。?

Post放body里的内容必须用[FromBody]且只能有一个这样的参数,一般为强类型,需要封装为复杂对像数据。

 

        [HttpPost]
        public string Post([FromBody]user json)
        {
            HttpContent cont=Request.Content;
            return "post," + ","+json.name;
        }
public class user
    {
        public int id { get; set; }
        public string name { get; set; }
    }

客户端请求时用JSON格式,且Content-Type为text/json,这样服务端接受到就直接是user对像。如果content-type不正确,服务端收到就是null。

如果只有一个参数[FromBoy]string v,客户端请求也必须json键值对,key为空??

对客户端来说不友好,老系统要改动。

 

asp.net发展了很多年,确实越来越丰富了,但总的来说还是封的太死,程序员越来越简单,头脑也简单,但不灵活。

 

2015.5.28 更新, web api一样可以获取参数

HttpContext.Current.Request.QueryString[""];
HttpContext.Current.Request.Form[""];
HttpContext.Current.Request.Files[""]
System.Web.HttpContext.Current.Request.QueryString

2017.5.18 获取get url querystring和post内容 (mvc controller更好用,可以返api也可以返view)

 

[HttpGet]
        [HttpPost]
        public string getmo()
        {
            string pname = System.Web.HttpContext.Current.Request.QueryString["pname"];

            //get url querystring
            string url = Request.RequestUri.Query;
            //post body
            string body=Request.Content.ReadAsStringAsync().Result;
            return "OK,"+url+","+body;
        }

web api的就是个方法,可以返回任何对像(自动序列化),包括string,string会加引号,可以返回httpresponse

HttpResponseMessage responseMessage =
                new HttpResponseMessage { Content = new StringContent(rtn, Encoding.GetEncoding("UTF-8"), "text/plain") };
            return responseMessage;

 

http://asdfblog.com/technology/accepting-raw-request-body-content-with-aspnet-web-api.html

http://weblog.west-wind.com/posts/2013/Apr/15/WebAPI-Getting-Headers-QueryString-and-Cookie-Values

posted @ 2015-02-28 16:56  chy710  阅读(176)  评论(0)    收藏  举报