首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >从MVC4站点向另一个站点发送命令

从MVC4站点向另一个站点发送命令
EN

Stack Overflow用户
提问于 2013-11-24 22:19:22
回答 1查看 98关注 0票数 0

我有两个站点:其中一个控制另一个通过Web发送一些命令。其思想是:控制器站点的操作向另一个站点发送一个命令,获取响应并执行一些业务规则,而不重定向到另一个站点。

我有大量的例子来解释如何通过jQuery实现这一点,但是我想让控制器将数据发布到另一个站点,而不是视图。

我在这个答案中找到了一种方法:How to use System.Net.HttpClient to post a complex type?,但是我想要一个JSON方法的答案。

有人能用JSON发布一个简单的例子来展示如何做到这一点吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-11-28 02:41:39

由于我没有找到我的问题的简短答案,我将张贴我已经做好的解决方案。

由于该方法使用了一个需要HttpClient语句的async方法,因此实现了对Task<ActionResult>的重新配置。另一个修改是在上下文中保存对象。

而不是使用:

代码语言:javascript
代码运行次数:0
运行
复制
context.SaveChanges();

你必须使用:

代码语言:javascript
代码运行次数:0
运行
复制
await context.SaveChangesAsync();

下面的代码实现了来自ASP.NET MVC4控制器的一个操作:

代码语言:javascript
代码运行次数:0
运行
复制
[HttpPost]
public async Task<ActionResult> Create(MyModel model)
{
    if (ModelState.IsValid)
    {
        // Logic to save the model.
        // I usually reload saved data using something kind of the statement below:

        var inserted = context.MyModels
            .AsNoTracking()
            .Where(m => m.SomeCondition == someVariable)
            .SingleOrDefault();

        // Send Command.
        // APIMyModel is a simple class with public properties.
        var apiModel = new APIMyModel();

        apiModel.AProperty = inserted.AProperty;
        apiModel.AnotherProperty = inserted.AnotherProperty;

        DataContractJsonSerializer jsonSer = new DataContractJsonSerializer(typeof(APIMyModel));

        // use the serializer to write the object to a MemoryStream 
        MemoryStream ms = new MemoryStream();
        jsonSer.WriteObject(ms, apiModel);
        ms.Position = 0;

        //use a Stream reader to construct the StringContent (Json) 
        StreamReader sr = new StreamReader(ms);
        // Note if the JSON is simple enough you could ignore the 5 lines above that do the serialization and construct it yourself 
        // then pass it as the first argument to the StringContent constructor 
        StringContent theContent = new StringContent(sr.ReadToEnd(), System.Text.Encoding.UTF8, "application/json"); 

        HttpClient aClient = new HttpClient();
        Uri theUri = new Uri("http://yoursite/api/TheAPIAction");
        HttpResponseMessage aResponse = await aClient.PostAsync(theUri, theContent);

        if (aResponse.IsSuccessStatusCode)
        {
            // Success Logic. Yay!
        }
        else
        {
            // show the response status code 
            String failureMsg = "HTTP Status: " + aResponse.StatusCode.ToString() + " - Reason: " + aResponse.ReasonPhrase;
        } 

        return RedirectToAction("Index");  
    }

    // if Model is not valid, you can put your logic to reload ViewBag properties here.
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20181824

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档