我有一个带有 .aspx 页面和代码隐藏文件的传统 .net Web 应用程序...
我想在 UI 上使用一些 jquery,并希望使用 json 服务来连接来自 jquery-easyui 的网格之类的东西。我见过一些不好的选择,比如使用 .aspx 页面返回 json 内容类型和独立的 wcf 示例,但我想在 IIS 中托管服务,因为应用程序位于托管的在线提供商上。
什么是最简单的方法可以很好地使用它,我如何在 VS2012 和我的本地 IIS 托管站点以及生产互联网站点中实现它?
您还可以将 WCF 服务直接包含到您的 Web 应用程序中并对其进行配置,以便它们返回并接收 JSON。它们看起来像这样:
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class YourServiceDoesJSON
{
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
public ReturnTypeThatWillBeTransformedIntoJSON GetWhatever(string parameterIfYouNeed)
{
// do something
return new ReturnTypeThatWillBeTransformedIntoJSON();
}
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)]
public SomethingElse PostWhatever()
{
...
}
}
此服务的配置文件如下所示:
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="WebApp.Folder.YourServiceDoesJSONAspNetAjaxBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="MetadataBehaviors" >
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
<services>
<service name="WebApp.Folder.YourServiceDoesJSON" behaviorConfiguration="MetadataBehaviors">
<endpoint address="" behaviorConfiguration="WebApp.Folder.YourServiceDoesJSONAspNetAjaxBehavior"
binding="webHttpBinding" contract="WebApp.Folder.YourServiceDoesJSON" />
</service>
</services>
注意:在我知道将 Web 应用程序转换为 MVC 如此容易之前,我就是这样做的;看我之前的回答;)
您可以使用 Web.Api 创建休息服务并将它们作为您网站的一部分进行托管。在这里查看完整的教程:http ://www.asp.net/web-api/tutorials/hands-on-labs/build-restful-apis-with-aspnet-web-api 。