消费使用WCF一个RESTful API JSON [英] Consuming a RESTful JSON API using WCF

查看:421
本文介绍了消费使用WCF一个RESTful API JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的WCF(和一般的.NET荒废了),所以有一个独特的机会,这是一个问题的回答,我只是错过了。

I'm new to WCF (and pretty rusty with .NET in general) so there's a distinct chance this is an answered question and I just missed it.

我建设将使用其后端一个RESTful基于JSON的API的ASP.NET MVC应用程序。我一直在寻找到如何去跟在.NET这样的API不同的选择,它看起来像WCF是最热门的选择远远。读入WCF一些我现在有一个基本的消费类,它的请求,这是一个开始。

I'm building an ASP.NET MVC app that will be using a RESTful JSON-based API for its backend. I've been looking into the different options for how to talk to such an API in .NET and it looks like WCF is the most popular choice by far. Reading into WCF some more I now have a basic consumer class that makes a request, which is a start.

但现在我需要用它做更多,我米赚不了多少进展。我需要一个POST发送到API使用JSON的身体。这是我到目前为止有:

But now I need to do more with it, and I'm not making much headway. I need to send a POST to the API with a JSON body. Here's what I have so far:

using System.ServiceModel;
using System.ServiceModel.Web;
using System.Runtime.Serialization;

namespace APIConsumer {
    [ServiceContract]
    public interface IAPIClient {
        [OperationContract]
        [WebInvoke(
            Method = "POST",
            BodyStyle = WebMessageBodyStyle.Bare,
            RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json,
            UriTemplate = "/session/login.json"
            )]
        string SessionLogin(string login_name);
    }

    public class APIClient : ClientBase<IAPIClient>, IAPIClient {
        public string SessionLogin(string login_name) {
            return this.Channel.SessionLogin(login_name);
        }
    }
}



我不明白出是通过一)邮政身体功放内的任何数据的正确方法; b)在适当的序列化的.NET对象为JSON的POST体。有怎样的工作,就在某个地方一个很好的例子?

What I can't figure out is the correct way to pass a) ANY data within the POST body & b) a proper serialized .NET object as JSON in the POST body. Is there a good example of how to work that out there somewhere?

推荐答案

如果你想知道如何格式化的JSON体你的岗位上操作SessionLogin,你的情况,那将是非常简单的。 JSON数据也只是:

If you are wondering how to format the JSON body of your POST to the operation SessionLogin, in your case, it would be very simple. The JSON data would just be:

{"login_name": "someuser"}

WCF框架将处理绘图数据,以你的操作,并会把值someUser所给参数LOGIN_NAME为您服务。这是你需要什么,还是有更复杂的情况下,您需要用?

The WCF framework will handle mapping that data to your operation, and will pass the value "someuser" to the parameter login_name for you. Is this what you needed, or was there a more complex scenario you needed help with?

这篇关于消费使用WCF一个RESTful API JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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