如何在MVC中将数据从MVC发布到webapi post方法 [英] How do I post data in http header from MVC to webapi post method

查看:64
本文介绍了如何在MVC中将数据从MVC发布到webapi post方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建应用程序原型,我在尝试从C#MVC Controller发送请求标头和正文中的数据,并创建了web api项目Post动作来处理请求。



我的代码是这样的::



MVC项目代码发布请求:



 public class HomeController:Controller 
{
public async Task< ActionResult> Index()
{
VM VM = new VM();
VM.Name =TEST Name;
VM.Address =TEST地址;

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 /值
公共IHttpActionResult邮政([FromBody] API.VM VM)
{
尝试
{
HttpRequestMessage重新=新HttpRequestMessage();

StreamWriter sw = new StreamWriter(@E:\ Applele \ 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();
返回Ok(成功);
}
catch(exception ex)
{
返回InternalServerError(ex);
}
}







我所理解的是[FromBody] API.VM vm从Http请求体获取数据,这意味着vm对象从HTTP Request body获取数据。我能够获取请求体。我无法理解如何从MVC控制器传递数据(我想传递JSON数据)并在WEB Api post方法中检索数据?



< b>我尝试了什么:



我使用过

 client.DefaultRequestHeaders.Add(username,test) ; 

在MVC项目中传递头数据和

 HttpRequestMessage re = new HttpRequestMessage(); 
var headers = re.Headers;
string token =;

if(headers.Contains(username))
{
token = headers.GetValues(username)。First();
}




用于获取数据的WEB API项目中的
但是我无法获得用户名值,< DIV类= h2_lin>解决方案

无需构建具有

新的对象的

HttpRequestMessage重新= <跨度类=代码 - 关键字>新 HttpRequestMessage();



使用静态请求而不是

 Request.Headers.TryGetValue(  username out   var  test); 


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 :

// POST api/values
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,

解决方案

No need to construct a new object with

HttpRequestMessage re = new HttpRequestMessage();


use static Request instead

Request.Headers.TryGetValue("username", out var test);


这篇关于如何在MVC中将数据从MVC发布到webapi post方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆