Asp.Net WebAPI 通过HttpContextBase或者HttpRquest 获取请求参数

WEBAPI中的Request是HttpRequestMessage类型,不能像Web传统那样有querystring和from 方法接收参数,而传统的HttpReqest的基类是HttpReqestBase

所以这里我们就直接使用(HttpContextBase)Request.Properties["MS_HttpContext"]

public void Post([FromBody]string value)
{
    HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context
    HttpRequestBase request = context.Request;//定义传统request对象            
    string name = request.Form["name"];    
}

1.获取遍历路由参数

//获取路由参数
IDictionary<string, object> dic = this.RequestContext.RouteData.Values;
StringBuilder builder = new StringBuilder();
foreach (var item in dic)
{
    builder.AppendFormat("key:{0},value:{1}", item.Key, item.Value);
    builder.AppendLine();
}
return builder.ToString();

2.遍历表单参数

////获取表单参数
HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context
HttpRequestBase request = context.Request;//定义传统request对象  
StringBuilder builder = new StringBuilder();
foreach (string item in request.Form.Keys)
{
    builder.AppendFormat("key:{0},value:{1}", item, request.Form[item]);
    builder.AppendLine();
}
return builder.ToString();

 

3.使用asp.net 的 HttpRquest 获取参数方式

        [HttpGet]
        public string Test1()
        {
            System.Web.HttpRequest req= System.Web.HttpContext.Current.Request;
            return req.QueryString["username"];
        }

 

posted @ 2015-12-30 19:51  天马3798  阅读(8047)  评论(0编辑  收藏  举报