我需要在C#中创建一个简单的Web服务,但我不知道从哪里开始(我之前用C#编写过UI应用程序,但我的所有Web体验都在Ruby on Rails中)。我从哪里开始?
Web服务的唯一客户端将是Ruby on Rails应用程序,因此不需要任何HTML呈现。我想只是返回一个XML或YAML格式的字符串,除非有一个更简单的方法。我不太热衷于SOAP,但如果它在C#和C#中很容易/很自然Ruby然后我会考虑它(或其他任何东西)。
答案 0 :(得分:1)
如果您有可以部署到的IIS 6或7环境,我只需创建一个ASP.NET-MVC 2应用程序。您可以使用Visual Studio模板创建一个,然后使用这样的控制器:
public class ApiController : Controller {
public ActionResult Index(string id) {
var xml = new XElement("results",
new XAttribute("myId", id ?? "null"));
return Content(xml.ToString(), "text/xml");
}
}
http://localhost:4978/Api/Index/test
等网址的输出为:
<results myId="test"/>
您可以轻松扩展它以返回您想要的任何格式(JSON等)。在任何情况下,ASP.NET MVC都可以很容易地创建一个REST API,它应该很容易从Ruby中使用。
答案 1 :(得分:1)
如果您想要WCF的灵活性,以下代码应该可以帮助您入门。 WCF可能比其他答案更复杂,但它提供了一些好处,如提高灵活性和从Windows服务托管服务。
创建一个看起来像这样的服务:
[ServiceContract]
public interface ITestService {
[OperationContract]
[WebGet(
BodyStyle = WebMessageBodyStyle.Bare,
ResponseFormat = WebMessageFormat.Xml
)]
XElement DoWork(string myId);
}
实施将是:
public class TestService : ITestService {
public XElement DoWork(string myId) {
return new XElement("results", new XAttribute("myId", myId ?? ""));
}
}
您的应用程序配置(web.config或app.config)文件将包含以下内容:
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="WebBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service name="WebApplication1.TestService">
<endpoint behaviorConfiguration="WebBehavior"
binding="webHttpBinding"
contract="WebApplication1.ITestService">
</endpoint>
</service>
</services>
</system.serviceModel>
如果您要在ASP.NET站点上托管它,那么您将拥有一个名为TestService.svc的文件,其中包含以下内容:
<%@ ServiceHost Language="C#" Debug="true"
Service="WebApplication1.TestService"
CodeBehind="TestService.svc.cs" %>
答案 2 :(得分:1)
我同意MVC路线。以下是我用来将对象踢出XML的内容:
public class XmlResult : ActionResult {
public XmlResult(object anObject) {
Object = anObject;
}
public object Object { get; set; }
public override void ExecuteResult(ControllerContext aContext) {
if (aContext == null) throw new Exception("Context cannot be null");
var response = aContext.HttpContext.Response;
response.ContentType = "application/xml";
SerializeObjectOn(Object, response.OutputStream);
}
private void SerializeObjectOn(object anObject, Stream aStream) {
var serializer = new XmlSerializer(anObject.GetType());
serializer.Serialize(aStream, anObject);
}
}
public class MyController : Controller {
public ActionResult Index() {
return new XmlResult(object);
}
}
申请
答案 3 :(得分:0)
这是一个简单的例子。
我使用Visual Studio创建.asmx文件并将其放在.cs代码后面。
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
namespace MyNamespace.Newstuff.Webservice
{
[WebService(Namespace = "http://iamsocool.com/MyNamespace/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class MyNamespace : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
}
}