我正在創建應用程序原型,我正在嘗試從 C# MVC 控制器發送請求標頭和正文中的數據,還創建了 web api 項目 Post 操作來處理請求。我的代碼是這樣的::發布請求的 MVC 項目代碼:public class HomeController : Controller { public async Task<ActionResult> Index() { VM VM = new VM(); VM.Name = " TEST Name"; VM.Address = " TEST Address "; using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:58297"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Add("username","test"); var json = JsonConvert.SerializeObject(VM); var content = new StringContent(json, Encoding.UTF8, "application/json"); var result1 = await client.PostAsync("api/Values/Post", content); } return View(); } }我在 WEB API 項目中的代碼: // POST api/valuespublic IHttpActionResult Post([FromBody]API.VM vm){ try { HttpRequestMessage re = new HttpRequestMessage(); StreamWriter sw = new StreamWriter(@"E:\Apple\txt.log", false); var headers = re.Headers; string token = ""; if (headers.Contains("username")) { token = headers.GetValues("username").First(); } sw.WriteLine("From header" + token); sw.WriteLine("From BODY" + vm.Name); sw.WriteLine("From BODY" + vm.Address); sw.WriteLine("Line2"); sw.Close(); return Ok("Success"); } catch (Exception ex) { return InternalServerError(ex); }}我所理解的是 [FromBody]API.VM vm 從 Http 請求正文中獲取數據,這意味著 vm 對象正在從 HTTP 請求正文中獲取數據。我能夠獲取請求正文。我無法理解如何從 MVC 控制器傳遞標頭中的數據(我想傳遞 JSON 數據)并在 WEB Api post 方法中檢索數據?我用過 client.DefaultRequestHeaders.Add("username","test"); 在 MVC 項目中傳遞標頭數據和在 WEB API 項目中獲取數據,但我無法獲取用戶名值。
2 回答

UYOU
TA貢獻1878條經驗 獲得超4個贊
為了通過 獲取數據headers,您需要啟用 CORS:Install-Package Microsoft.AspNet.WebApi.Cors在您的項目中,然后在您的Register方法中WebApiConfig.cs,添加以下行:EnableCors();。
完成后,您可以訪問標頭變量:
IEnumerable<string> values = new List<string>();
actionContext.Request.Headers.TryGetValues("username", out values);

慕村225694
TA貢獻1880條經驗 獲得超4個贊
您可以使用該 Web API 方法中的以下行將所有標頭傳遞給 Web API 的方法:
HttpActionContext actionContext = this.ActionContext;
var headers = actionContext.Request.Headers;
- 2 回答
- 0 關注
- 80 瀏覽
添加回答
舉報
0/150
提交
取消