简体   繁体   English

HttpClient C#发布

[英]HttpClient C# Post

I've done a POST request with the HTTPClient class but now I'm struggling a bit. 我已经用HTTPClient类完成了POST请求,但是现在有点挣扎了。 How can I achieve displaying it on my website? 如何在我的网站上显示它? The goal is to post a json ( currently in a string) and then display it on the site again. 目标是发布json(当前为字符串),然后再次将其显示在网站上。 As you can see my POST command goes to the home controller in mvc and then the about action. 如您所见,我的POST命令转到mvc中的home控制器,然后转到about操作。 How can I now get the data and return it to a view? 现在如何获取数据并将其返回到视图?

public ActionResult About(string json)

Does adding paramters like this work? 像这样添加参数会起作用吗? And if so how do I do it properly? 如果是的话,我该怎么做呢?

This is the method call: 这是方法调用:

post(JsonConvert.SerializeXmlNode(pack));

This is the method itself: 这是方法本身:

async Task post(string jsonText)
{
                    // Create a New HttpClient object and dispose it when done, so the app doesn't leak resources
      using (HttpClient client = new HttpClient())
      {
      // Call asynchronous network methods in a try/catch block to handle exceptions
          try
          {
               StringContent json = new StringContent(jsonText, Encoding.UTF8, "application/json");
               HttpResponseMessage response = await client.PostAsync("http://localhost:60000/home/about", json);
               response.EnsureSuccessStatusCode();
               string responseBody = await response.Content.ReadAsStringAsync();
               // Above three lines can be replaced with new helper method below
               // string responseBody = await client.GetStringAsync(uri);

               Console.WriteLine(responseBody);
               }catch (HttpRequestException e)
               {
                    Console.WriteLine("\nException Caught!");
                    Console.WriteLine("Message :{0} ", e.Message);
               }
           }
      }

Update 更新

How can i give the PostAsync command my own class? 我如何给PostAsync命令我自己的课? It forces me give it a HttpContent. 它迫使我给它一个HttpContent。

As suggested i have created a new method to cache the whole data but what parameter do i have to give the method which saves the data to receive the class or httpcontent? 如建议的那样,我创建了一个新方法来缓存整个数据,但是我必须给哪个参数以保存数据的方法以接收类或httpcontent? (in the controller) (在控制器中)

 [HttpPost]
        public HttpResponseMessage Data(//What parameter?)
        {
            //SaveData

            return new HttpResponseMessage(HttpStatusCode.OK);

        }

So your question would be better asked as "How do I return json from an MVC Controller" I think. 因此,我认为您的问题最好问为“如何从MVC控制器返回json”。 If that's the case then take a look at this... 如果是这样,那么看看这个...

ASP.NET MVC controller actions that return JSON or partial html 返回JSON或部分html的ASP.NET MVC控制器操作

UPDATE #1 更新#1

So I think the OP is actually trying to post from a console app and then be able to view the json that was sent from that console app within a website? 因此,我认为OP实际上正在尝试从控制台应用程序发布,然后能够查看网站内从该控制台应用程序发送的json?

OP, When the console app posts the data, that's a single request with no persistence of the data unless YOU persist it. OP,当控制台应用程序发布数据时,这是单个请求,没有数据的持久性,除非您将其持久化。 You would need to store that json string somewhere. 您需要将json字符串存储在某个地方。 Depending on the need, this could be a DB or some cache. 根据需要,它可以是数据库或某些缓存。

You would then need to amend your About method to retrieve the json from that storage location, deserialise it and return it within the ViewModel. 然后,您需要修改About方法,以从该存储位置检索json,反序列化并在ViewModel中返回它。

Alternatively, you could swap out the About method for an API call that simply retrieves the json and returns it - then you would need to implement a client-side get from your web page to retrieve the json from the api and display it. 或者,您可以将About方法换为仅检索json并返回它的API调用-然后,您需要从网页上实现客户端get,以从api检索json并显示它。

Various options, various pros & cons to all of them and all dependant upon your requirements. 各种选择,各种优点和缺点,都取决于您的要求。

UPDATE #2 更新#2

Further to OP adding a comment to this answer... 在OP进一步为该答案添加评论...

I would suggest you define the data that is going to posted between the Console application and your MVC application - don't just use a string. 我建议您定义要在控制台应用程序和MVC应用程序之间发布的数据-不要只使用字符串。 I would suggest adding a third project as a class assembly and define this class in here. 我建议添加第三个项目作为类程序集,并在此处定义该类。 You can then add a reference to this new project in both the Console project and the MVC project so that they can both reference the new class. 然后,您可以在Console项目和MVC项目中都添加对该新项目的引用,以便它们都可以引用新类。

You currently have two uses of your About method, your Console app is POSTING data and your View is GETTING data - you should separate these things into two separate Methods and decorate each with appropriate attributes [HttpPost] and [HttpGet]. 当前,关于About方法有两种用法,控制台应用程序是POSTING数据,视图是GETTING数据-您应该将这些东西分成两个单独的方法,并分别用[HttpPost]和[HttpGet]属性修饰。

Update your Console application to use your new class, serialise it and post it similar to how you're currently doing it - the url should use the method from above decorated with the [HttpPost]. 更新控制台应用程序以使用您的新类,对其进行序列化并以类似于您当前的方式进行发布-网址应使用上面用[HttpPost]装饰的方法。

Adjust your [HttpPost] method to take the object you posted and store it somewhere. 调整[HttpPost]方法,以接收发布的对象并将其存储在某处。 I get the impression this is a basic project or even a POC so just cache it for now. 我觉得这是一个基础项目,甚至是POC,因此暂时将其缓存。 Here's an article about caching 这是有关缓存的文章

Cache in-memory in ASP.NET Core 在ASP.NET Core中缓存内存

You may want to put the requests into a collection (List) and keep the collection itself in the cache - this will depend on what you need to display in your webpage. 您可能希望将请求放入集合(列表)中,并将集合本身​​保留在缓存中-这取决于您需要在网页中显示的内容。

In you [HttpGet] method, you now need to retrieve everything from the cache and pass it into your ViewModel - as you should now have a nice MyClass object (or List) this should be straight forward to render - in fact VS will likely generate the view for you! 在[HttpGet]方法中,您现在需要从缓存中检索所有内容并将其传递到ViewModel中-因为您现在应该有一个不错的MyClass对象(或List),应该可以直接呈现它-实际上VS可能会生成适合您的风景!

There's really far too much to go into in this thread but hopefully this helps. 在这个线程中确实有太多内容要讨论,但是希望这会有所帮助。 I don't think it's going to be possible to post entire code samples unfortunately. 我认为不幸的是不可能发布整个代码示例。

Hopefully while not the answer you may have been looking for, it'll help. 希望虽然不是您一直在寻找的答案,它会有所帮助。

UPDATE #3 更新#3

Ok - I've created a solution that should demonstrate what you need to do. 好的-我已经创建了一个解决方案,该演示应演示您需要做的事情。

I'm sure there are other/better ways to do what you want to do BUT...hopefully this will help you understand the concepts. 我确信还有其他/更好的方法可以完成您想做的事情...希望这将帮助您理解这些概念。

https://github.com/dotnetter/ConsoleHttpExample https://github.com/dotnetter/ConsoleHttpExample

Just clone the repo and configure in VS to run both the website and the console app. 只需克隆存储库并在VS中进行配置即可运行网站和控制台应用程序。

you should access json data like this : 您应该像这样访问json数据:

public ActionResult Insert(dynamic[] dynamicClass)
    {

        try
        {
            //do something...

var movie = //convert dynamicClass to whatever you want...  ;
             return View(movie);

        }
        catch (Exception ex)
        {
            // Otherwise return a 400 (Bad Request) error response
            return BadRequest(ex.ToString());
        }


    }

and for your question how to use in the view, its up to you. 对于您的问题,如何在视图中使用,取决于您。 basiclly if youre using MVC your can store it in some class and use it like this(in cshtml file): 基本上,如果您使用MVC,则可以将其存储在某个类中并像这样使用(在cshtml文件中):

@model MvcMovie.Models.Movie

@{
    ViewData["Title"] = "Details"; 
}

<h1>Details</h1>

<div>
    <h4>Movie</h4>
    <hr />
    <dl class="row">
       <dt class="col-sm-2">
            @Html.DisplayNameFor(model => model.Title)
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.Title)
        </dd>
        <dt class="col-sm-2">
            @Html.DisplayNameFor(model => model.ReleaseDate)
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.ReleaseDate)
        </dd>
        <dt class="col-sm-2">
            @Html.DisplayNameFor(model => model.Genre)
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.Genre)
        </dd>
        <dt class="col-sm-2">
            @Html.DisplayNameFor(model => model.Price)
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.Price)
        </dd>
    </dl>
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM