WCF REST 服务 JSON 发布数据

发布于 2024-10-25 04:32:18 字数 2453 浏览 2 评论 0原文

寻找有关 wcf 4 Rest 服务的一些指导,该服务基于 VS2010 中的 WCF REST Template 40(CS) 扩展。在过去的几天里,我一直试图让这个虫子工作,审查其他帖子,虽然我已经接近了,但我似乎无法越过终点线。经过多次挫折后,它终于到达服务并发布(使用 fiddler 请求构建器),但方法参数显示为 null,但它在请求构建器中被正确设置。我猜测此时可能是配置问题,但随着截止日期的临近,我没有时间进行更多研究。 FWIW,在调试中,jsonstring 变量为空。诚然,我自己是一个菜鸟问题,因为这是我第一次通过 REST,任何帮助将不胜感激!

提前致谢。

web.config

<system.web>
  '<compilation debug="true" targetFramework="4.0" />
</system.web>

<system.webServer>
 <modules runAllManagedModulesForAllRequests="true">
   <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
 </modules>
</system.webServer>

<system.serviceModel>
 <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
 <standardEndpoints>
   <webHttpEndpoint>
     <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/>
   </webHttpEndpoint>
 </standardEndpoints>
</system.serviceModel>

global.asax.cs

   public class Global : HttpApplication
  {
      void Application_Start(object sender, EventArgs e)
      {
         RegisterRoutes();
      }

      private void RegisterRoutes()
      {
         RouteTable.Routes.Add(new ServiceRoute("Scoring", new WebServiceHostFactory(), typeof(ScoringSvc)));
      }
   }

服务代码

[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class ScoringSvc 
{
   [OperationContract]
   [WebInvoke
      (Method = "POST",
      BodyStyle = WebMessageBodyStyle.WrappedRequest,
      RequestFormat=WebMessageFormat.Json,
      ResponseFormat=WebMessageFormat.Json)]
   public string BOB(string jsonstring)
   {
      return "Received: " + jsonstring;
   }
}

Fiddler 请求标头

Host: localhost
Content-Length: 20
Content-Type: application/json; charset=UTF-8

请求正文

{"Name":"Frank"}

来自 fiddler 的原始响应

HTTP/1.1 200 OK
Cache-Control: private
Content-Length: 12
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Mon, 21 Mar 2011 21:31:14 GMT

"Received: "

Looking for some guidance on a wcf 4 rest service which is based on the WCF REST Template 40(CS) extension in VS2010. I've spent the last couple of days trying to get this bugger to work, reviewing other posts, and while I've gotten close, I can't seem to cross the finish line. After much frustration, it is finally hitting the service and posting (using fiddler request builder) but the method parameter is coming across as null, but it's being set properly in the request builder. I'm guessing that it may be a config issue at this point, but as the deadline looms, I'm running out of time for more research. FWIW, in debugging, the jsonstring variable is null. Self admittedly kind of a noob question as this is the first time through REST for me, any help would be much appreciated!

Thanks in advance.

web.config

<system.web>
  '<compilation debug="true" targetFramework="4.0" />
</system.web>

<system.webServer>
 <modules runAllManagedModulesForAllRequests="true">
   <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
 </modules>
</system.webServer>

<system.serviceModel>
 <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
 <standardEndpoints>
   <webHttpEndpoint>
     <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/>
   </webHttpEndpoint>
 </standardEndpoints>
</system.serviceModel>

global.asax.cs

   public class Global : HttpApplication
  {
      void Application_Start(object sender, EventArgs e)
      {
         RegisterRoutes();
      }

      private void RegisterRoutes()
      {
         RouteTable.Routes.Add(new ServiceRoute("Scoring", new WebServiceHostFactory(), typeof(ScoringSvc)));
      }
   }

Service code

[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class ScoringSvc 
{
   [OperationContract]
   [WebInvoke
      (Method = "POST",
      BodyStyle = WebMessageBodyStyle.WrappedRequest,
      RequestFormat=WebMessageFormat.Json,
      ResponseFormat=WebMessageFormat.Json)]
   public string BOB(string jsonstring)
   {
      return "Received: " + jsonstring;
   }
}

Fiddler request header

Host: localhost
Content-Length: 20
Content-Type: application/json; charset=UTF-8

request body

{"Name":"Frank"}

Raw response from fiddler

HTTP/1.1 200 OK
Cache-Control: private
Content-Length: 12
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Mon, 21 Mar 2011 21:31:14 GMT

"Received: "

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

安人多梦 2024-11-01 04:32:18

偶然发现此链接 WCF + REST:请求数据在哪里?并看到格伦的响应,将流传递给该方法,然后使用流读取器将其分解为字符串以获取表单发布数据。

修改原型服务代码如下

[OperationContract]
[WebInvoke
   (UriTemplate="/BOB",
    Method = "POST",
    BodyStyle = WebMessageBodyStyle.WrappedRequest)]
public string BOB (Stream streamdata)
{
    StreamReader reader = new StreamReader(streamdata);
    string res = reader.ReadToEnd();
    reader.Close();
    reader.Dispose();
    return "Received: " + res;
}

这似乎可以解决问题,完整的 json 数组在流中传递,读入本地字符串,然后我可以使用 json.net 攻击它以序列化到字典中/从字典中序列化以传递到业务逻辑。不是很漂亮,但很实用。

Stumbled across this link WCF + REST: Where is the request data? and seen Glenn's response to pass a stream to the method and then rip that apart with a streamreader into a string to get the form post data.

Modified the prototype service code as follows

[OperationContract]
[WebInvoke
   (UriTemplate="/BOB",
    Method = "POST",
    BodyStyle = WebMessageBodyStyle.WrappedRequest)]
public string BOB (Stream streamdata)
{
    StreamReader reader = new StreamReader(streamdata);
    string res = reader.ReadToEnd();
    reader.Close();
    reader.Dispose();
    return "Received: " + res;
}

And that seems to do the trick, the full json array is passed in the stream, read into the local string, and I can then attack it using json.net to serialize into / from a dictionary to pass to the business logic. Not really pretty, but functional.

风为裳 2024-11-01 04:32:18

您是否尝试过在请求正文(在 fiddler 的请求生成器内)中输入 {"jsonstring":"Frank"} ?

Have you tried entering {"jsonstring":"Frank"} in the request body(inside fiddler's Request Builder)?

有木有妳兜一样 2024-11-01 04:32:18

我使用这个并工作:

[WebInvoke(ResponseFormat = WebMessageFormat.Json, 
           RequestFormat = WebMessageFormat.Json,
           BodyStyle = WebMessageBodyStyle.WrappedRequest,
           Method = "POST",
           UriTemplate = "setExpositions?shelfId={shelfId}")]
[OperationContract]
public bool SetExpositions(int shelfId, List<WcfExposition> expositions)
{
}

shelfId 在 GET 中传递,并且说明作为 JSON 数据在消息正文中传递。

I use this one and works:

[WebInvoke(ResponseFormat = WebMessageFormat.Json, 
           RequestFormat = WebMessageFormat.Json,
           BodyStyle = WebMessageBodyStyle.WrappedRequest,
           Method = "POST",
           UriTemplate = "setExpositions?shelfId={shelfId}")]
[OperationContract]
public bool SetExpositions(int shelfId, List<WcfExposition> expositions)
{
}

where shelfId is passed in GET, and expositions are passed in the message body as JSON data.

对岸观火 2024-11-01 04:32:18

我认为 BodyStyle = WebMessageBodyStyle.WrappedRequest 中可能存在问题,尽管文档完全不清楚,但它会期望元素用方法名称包装。

将其展开,并将请求正文设置为 '{"Name":"Frank"}' (注意它周围的单引号。您实际上发布的内容是包含 JSON 的字符串。我不知道为什么你想要这个。它让我想起了http://thedailywtf.com/Articles/XMLd-XML .aspx 他们将 xml 放入他们的 xml 中,您将 JSON 放入您的 JSON 中。

I think there may be an issue in BodyStyle = WebMessageBodyStyle.WrappedRequest, which will - I think, though the documentation is wholly unclear - expect the element to be wrapped with the method name.

Set that unwrapped, and set the request body to '{"Name":"Frank"}' (notice the single quotes around it. What you are actually posting a string containing JSON. I have no idea why you would want this. It reminds me off http://thedailywtf.com/Articles/XMLd-XML.aspx where they are putting xml in their xml. You are putting JSON in your JSON.

凹づ凸ル 2024-11-01 04:32:18

您是否尝试过 [WebGet(UriTemplate = .. ] 属性而不是帖子来查看这是否有效?这是一个示例 - http://blogs.msdn.com/b/kaevans/archive/ 2007/09/04/创建-a-json-service-with-webget-and-wcf-3-5.aspx

Have you tried the [WebGet(UriTemplate = .. ] attribute instead of the post to see if that would work? Here is an example - http://blogs.msdn.com/b/kaevans/archive/2007/09/04/creating-a-json-service-with-webget-and-wcf-3-5.aspx

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文