2013-08-11 26 views
5

Tôi đã tạo một C# ASP.Net JSON WebService. Nhưng tôi có những rắc rối lớn với việc đọc dữ liệu từ WebService này bởi vì trong mắt tôi đầu ra không phải là một định dạng JSON hợp lệ?Cách tạo JSON WebService trong C# ASP.Net với đầu ra JSON hợp lệ và truy vấn với JQuery/Ajax

Thông thường bạn sẽ nhận được [đối tượng, đối tượng] trở lại dưới dạng dữ liệu. Nhưng tôi nhận được [đối tượng, tài liệu] Điều tôi đang làm sai hoặc những gì tôi đang thiếu?

sản lượng hiện tại của tôi trông giống như sau:

<?xml version="1.0" encoding="utf-8"?> 
<string xmlns="http://tempuri.org/">{ 
    "Email": "[email protected]", 
    "Active": true, 
    "CreatedDate": "2013-01-20T00:00:00Z", 
    "Roles": [ 
    "User", 
    "Admin" 
    ] 
}</string> 

Đây là cuộc gọi JQuery-Ajax của tôi:

$.ajax({ 
    type: "GET", 
    //dataType: "json", <-- When I uncomment this line the request fails :(
    url: "http://webservices.domain.local/service.asmx/getData?name=", 

    success: function(data){ 
     console.log(data); // Output is: [object Document] instead of [object, object] 
    }, 
    error: function(XMLHttpRequest, textStatus, errorThrown){ 

    } 
}); 

Đây là mã từ WebService tôi:

using System; 
using System.Collections.Generic; 
using System.Data; 
using System.Linq; 
using System.Runtime.Serialization; 
using System.Web; 
using System.Web.Script.Serialization; 
using System.Web.Script.Services; 
using System.Web.Services; 
using Newtonsoft.Json; 

namespace DataWebService 
{ 
    /// <summary> 
    /// Summary description for Service1 
    /// </summary> 
    [WebService(Namespace = "http://tempuri.org/")] 
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
    [System.ComponentModel.ToolboxItem(false)] 
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService] 
    public class SPServices : System.Web.Services.WebService 
    { 
     [WebMethod] 
     [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)] 
     public string getData(string name) 
     { 
      Account account = new Account 
      { 
       Email = "[email protected]", 
       Active = true, 
       CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc), 
       Roles = new List<string> 
        { 
        "User", 
        "Admin" 
        } 
      }; 
      return JsonConvert.SerializeObject(account, Formatting.Indented); 
     } 
    } 

    public class Account 
    { 
     public string Email { get; set; } 
     public bool Active { get; set; } 
     public DateTime CreatedDate { get; set; } 
     public IList<string> Roles { get; set; } 
    } 
} 

Các webconfig File:

<?xml version="1.0"?> 
<configuration> 
    <configSections> 
     <!--<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"> 
     <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"> 
      <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/> 
      <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"> 
      <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere" /> 
      <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" /> 
      <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" /> 
      <section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" /> 
      </sectionGroup> 
     </sectionGroup> 
     </sectionGroup>--> 
    </configSections> 
    <appSettings/> 
    <connectionStrings/> 
    <system.web> 
     <webServices> 
     <protocols> 
      <add name="HttpGet"/> 
      <add name="HttpPost"/> 
     </protocols> 
     </webServices> 
     <compilation debug="true" > 
      <assemblies> 
      <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> 
      <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> 
      <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> 
      <add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> 
      </assemblies> 
     </compilation> 
    <!-- 
     The <authentication> section enables configuration 
     of the security authentication mode used by 
     ASP.NET to identify an incoming user. 
    --> 
    <authentication mode="Windows" /> 
    <!-- 
     The <customErrors> section enables configuration 
     of what to do if/when an unhandled error occurs 
     during the execution of a request. Specifically, 
     it enables developers to configure html error pages 
     to be displayed in place of a error stack trace. 

     <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm"> 
     <error statusCode="403" redirect="NoAccess.htm" /> 
     <error statusCode="404" redirect="FileNotFound.htm" /> 
     </customErrors> 
    --> 
     <pages> 
     <controls> 
      <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> 
      <add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> 
     </controls> 
     </pages> 

     <httpHandlers> 
     <remove verb="*" path="*.asmx"/> 
     <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> 
     <!--<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> 
     <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>--> 
     </httpHandlers> 
     <httpModules> 
     <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> 
     </httpModules> 
    </system.web> 
    <system.codedom> 
     <compilers> 
     <compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" 
        type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> 
      <providerOption name="CompilerVersion" value="v3.5"/> 
      <providerOption name="WarnAsError" value="false"/> 
     </compiler> 
     </compilers> 
    </system.codedom> 
    <!-- 
     The system.webServer section is required for running ASP.NET AJAX under Internet 
     Information Services 7.0. It is not necessary for previous version of IIS. 
    --> 
    <system.webServer> 
     <validation validateIntegratedModeConfiguration="false"/> 
     <modules> 
     <remove name="ScriptModule" /> 
     <add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> 
     </modules> 
     <handlers> 
     <remove name="WebServiceHandlerFactory-Integrated"/> 
     <remove name="ScriptHandlerFactory" /> 
     <remove name="ScriptHandlerFactoryAppServices" /> 
     <remove name="ScriptResource" /> 
     <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" 
      type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> 
     <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" 
      type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> 
     <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> 
     </handlers> 
     <httpProtocol> 
     <customHeaders> 
      <add name="Access-Control-Allow-Origin" value="*" /> 
      <add name="Access-Control-Allow-Headers" value="Content-Type" /> 
     </customHeaders> 
     </httpProtocol> 
    </system.webServer> 
    <runtime> 
     <assemblyBinding appliesTo="v2.0.50727" xmlns="urn:schemas-microsoft-com:asm.v1"> 
     <dependentAssembly> 
      <assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/> 
      <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/> 
     </dependentAssembly> 
     <dependentAssembly> 
      <assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/> 
      <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/> 
     </dependentAssembly> 
     </assemblyBinding> 
    </runtime> 
</configuration> 

Tôi sẽ thực sự hạnh phúc nếu ai đó có thể giúp tôi ... Tôi dành cả ngày cuối tuần vào này nhưng tôi couldn't tìm một giải pháp cho điều này ...: - (

+0

Bạn tạo XML thay vì JSON và ajax bởi mặc định nếu nội dung là xml, nó tạo tài liệu xml. – jcubic

+0

Tại sao tôi tạo XML được insted của JSON? Trong WebService của tôi, tôi đã xác định rằng giá trị trả về phải là JSON và tôi cũng đã cố gắng sử dụng Thư viện JSON ... Bất kỳ ý tưởng nào về cách tôi có thể thay đổi đầu ra thành JSON? – Simon

+0

Có vẻ như câu trả lời này đã được trả lời trước đây: http://stackoverflow.com/questions/5300855/how-can-my-asp-net-c-sharp-class-return-a-json-format –

Trả lời

1

Hãy thử sử dụng ASP.net web-api (một phần của MVC 4) thay vì làm dự án cốt lõi của bạn. khi một bộ điều khiển hành động trả về một đối tượng, nó sẽ tự động được tuần tự hóa thành xml hoặc json tùy thuộc vào yêu cầu. Đó là trình duyệt của bạn yêu cầu một trong hai và dịch vụ cung cấp.

Họ thậm chí đã tách thư viện MS cũ cho JSON và thay thế bằng newtonsoft. Điều này có nghĩa rằng một số kịch bản được hỗ trợ bởi serialization json và không xml serialization. Nếu bạn cần những tính năng đó, bạn có thể xóa xml-serializer mặc định và chỉ hỗ trợ json.

Chúc may mắn! :)

+0

mh ... Tôi nghĩ rằng tôi không thực sự hiểu ý của bạn ... có lẽ bạn có thể mô tả nó với một chút chi tiết hơn để tôi có được hướng đi đúng không? (hoặc có thể một số liên kết?) – Simon

+0

Anh ấy có nghĩa là: http://james.newtonking.com/pages/json-net.aspx –

+0

Ý tôi là chủ yếu http://www.asp.net/web-api, đó là hit đầu tiên trên google cho asp.net web-api.Nó sẽ cho bạn biết mọi thứ bạn cần biết. Chủ yếu là tôi đang nghĩ rằng bạn đang làm phức tạp những thứ cho chính mình bằng cách chọn một công nghệ cũ hơn chung hơn một mới sắp xếp hợp lý hơn. Vì vậy, tôi chỉ cho bạn theo hướng của một công nghệ mà nên làm cho cuộc sống dễ dàng hơn cho bạn. Tuy nhiên tôi sẽ không làm toàn bộ công việc cho bạn. :) – Mithon

7

Thêm sử dụng sau đây:

using System.Web.Mvc; 

Và thay đổi tole của bạn để:

[WebMethod] 
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)] 
public JsonResult getData(string name) 
     { 
      Account account = new Account 
      { 
       Email = "[email protected]", 
       Active = true, 
       CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc), 
       Roles = new List<string> 
        { 
        "User", 
        "Admin" 
        } 
      }; 
      return Json(account); 
     } 

tôi nghĩ rằng nó sẽ làm việc như thế này