.net C# Web Api 調試獲取請求的參數,通過HttpContextBase獲取請求參數


轉自:http://www.cnblogs.com/tianma3798/p/5089890.html

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();
復制代碼


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM