I am creating prototype of application where in I am trying to send data in request header and body from C# MVC Controller and also created web api project Post action to process the request.
My code goes like this::
MVC Project code to Post Request:
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();
}
}
My code in WEB API project :
public 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);
}
}
What I have understood is [FromBody]API.VM vm gets data from Http request body which means vm object is getting data from HTTP Request body.I am able to get request body. I am not able to understand how do I pass data in header from MVC controller (I want to pass JSON Data) and retrieve data in WEB Api post method?
What I have tried:
I have used
client.DefaultRequestHeaders.Add("username","test");
in MVC project to pass header data and
HttpRequestMessage re = new HttpRequestMessage();
var headers = re.Headers;
string token = "";
if (headers.Contains("username"))
{
token = headers.GetValues("username").First();
}
in WEB API project to get data but I am not able to get username value,