locked
getting json data from odata domain service RRS feed

  • Question

  • I have been driving myself batty trying to get my odata service to return json, and I am almost ready to give up.

    Can someone please offer any guidance as to what I am doing wrong. Here is my app config file, as well as the code for my data service.

    <?xml version="1.0" encoding="utf-8"?>
    <!--
      For more information on how to configure your ASP.NET application, please visit
      http://go.microsoft.com/fwlink/?LinkId=169433
      -->
    <configuration>
      <configSections>
        <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
        <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
      </configSections>
      <system.web>
    	  
        <compilation debug="true" targetFramework="4.5" />
        <httpRuntime targetFramework="4.5"   requestValidationMode="2.0" />
    	  <pages validateRequest="false" />
      </system.web>
      <connectionStrings>
        <add name="ProdContext" connectionString="Data Source=cnndcvcop007.nndc.kp.org;Initial Catalog=IMGDCSProd;User Id=webuser; Password=webuser1;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
      </connectionStrings>
      <entityFramework>
        <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
          <parameters>
            <parameter value="v11.0" />
          </parameters>
        </defaultConnectionFactory>
      </entityFramework>
        <system.diagnostics>
        <sources>
          <source name="System.ServiceModel"
                  switchValue="Information, ActivityTracing"
                  propagateActivity="true">
            <listeners>
              <add name="traceListener"
                  type="System.Diagnostics.XmlWriterTraceListener"
                  initializeData= "C:\Temp\Traces.svclog" />
            </listeners>
          </source>
        </sources>
      </system.diagnostics>
        
      <system.serviceModel>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
    	  <standardEndpoints>
    		  <webHttpEndpoint>
    			  <!-- 
                Configure the WCF REST service base address via the global.asax.cs file and the default endpoint 
                via the attributes on the <standardEndpoint> element below
            -->
    			  <standardEndpoint name="" helpEnabled="true"
    		 defaultOutgoingResponseFormat="Json"/>
    		  </webHttpEndpoint>
    	  </standardEndpoints>
    	  
       <diagnostics>
          <messageLogging logEntireMessage="true" logMalformedMessages="true"
            logMessagesAtServiceLevel="true" logMessagesAtTransportLevel="true" />
        </diagnostics>
      </system.serviceModel>
    </configuration>

    and here is the code for the  service itself.  right now I am only in dev so I am not worried about security for now.

    using DataLayer;
    using DataLayer.Context;
    using DataLayer.Repositories;
    using DomainObj.Models;
    //------------------------------------------------------------------------------
    // <copyright file="WebDataService.svc.cs" company="Microsoft">
    //     Copyright (c) Microsoft Corporation.  All rights reserved.
    // </copyright>
    //------------------------------------------------------------------------------
    using System;
    using System.Collections.Generic;
    using System.Data.Services;
    using System.Data.Services.Common;
    using System.Linq;
    using System.ServiceModel.Web;
    using System.Web;
    using DataServicesJSONP;
    namespace MWData
    {
    	[JSONPSupportBehavior]
        public class MainWinServiceOdata : DataService<MwContext>
        {
            // This method is called only once to initialize service-wide policies.
            public static void InitializeService(DataServiceConfiguration config)
            {
                // TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
                // Examples:
                config.UseVerboseErrors = true;
                config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
                config.SetServiceOperationAccessRule("GetAllMaintWindows", ServiceOperationRights.AllRead);
                config.SetServiceOperationAccessRule("GetMaintWindowsWintel", ServiceOperationRights.AllRead);
                config.SetServiceOperationAccessRule("GetMaintWindowsByTower", ServiceOperationRights.AllRead);
                config.SetServiceOperationAccessRule("GetMaintEnv", ServiceOperationRights.AllRead);
                config.SetServiceOperationAccessRule("GetUserName", ServiceOperationRights.AllRead);
                config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;
            }
            [WebGet]
            public string GetUserName()
            {
                string networkusr = String.Empty;
                if (HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    // Get the current user
                    string val =  HttpContext.Current.User.Identity.Name;
                    networkusr = val.Substring(3, val.Length -3);
                    using (var mw = new MwRepository(new UOWMaintWindow()))
                    {
                        networkusr = mw.getUzrNme(networkusr);
                    }
                }
                else
                {
                    networkusr = "Not Found";
                }
                return networkusr;
            }
            [WebGet]
            public IQueryable<tblMW> GetMaintWindowsWintel()
            {
                using (var mw = new MwRepository(new UOWMaintWindow()))
                {
                    return mw.GetMaintWindowsWintel();
                }
            }
            [WebGet(UriTemplate="GetMaintWindowsByTower", ResponseFormat = WebMessageFormat.Json, RequestFormat=WebMessageFormat.Json)]
            
            public IQueryable<tblMW> GetMaintWindowsByTower(string tower,string Env)
            {
                using (var mw = new MwRepository(new UOWMaintWindow()))
                {
                    return mw.GetMaintWindowsbyTower(tower, Env).Take(5);
                }
            }
    		[WebGet]
            public IQueryable<string> GetMaintEnv()
            {
    			WebOperationContext.Current.OutgoingResponse.Format =
    																			 WebMessageFormat.Json;  
                using (var mw = new MwRepository(new UOWMaintWindow()))
                {
                    return mw.GetMWEnvironments();
                }
            }
            [WebGet]
            public IQueryable<tblMW> GetAllMaintWindows()
            {
                using (var mw = new MwRepository(new UOWMaintWindow()))
                {
                    // Ensure user is authenticated
                    if (HttpContext.Current.User.Identity.IsAuthenticated)
                    {
                        // Get the current user
                        string networkusr = HttpContext.Current.User.Identity.Name;
                    }
                    return mw.All.ToList().AsQueryable();
                }
            }
        }
    }

    Wednesday, October 31, 2012 9:50 PM

Answers

  • ok. so I figured this out because nobody sent me anything back. Here is what I found. if when I was in fiddler, I changed the accept header to Accept:application/json;odata=verbose   

    then in fiddler, I would get back proper json. I thought awesome... but.... it was not so awesome as I was to find out latter.

    When I went back into my html page, and hit the service with jquery 1.8 and change the contenttype to be applicatoin/json:odata=verbose....

    death to my progress...

    so..

    after some digging, here is what worked for me

    in my ajax call, I set the beforesend:function(xhr){

    xhr.setRequestHeader("Accept","application/json;odata=verbose");

    xhr.setRequestHeader("MaxDataServiceVersion","3.0");

    }

    apparently v3.0 is getting ready for something called json light.. and Microsoft has done this change to support it. In the future, when you do the application/json   it will return jsonlight..

    but that part is not turned on yet.

    so all the video watching on the json odata works with v2.0, but when you go to v3.0 you get a new mix.

    Happy javascript 


    Patrick

    Thursday, November 1, 2012 5:01 PM

All replies

  • ok. so I figured this out because nobody sent me anything back. Here is what I found. if when I was in fiddler, I changed the accept header to Accept:application/json;odata=verbose   

    then in fiddler, I would get back proper json. I thought awesome... but.... it was not so awesome as I was to find out latter.

    When I went back into my html page, and hit the service with jquery 1.8 and change the contenttype to be applicatoin/json:odata=verbose....

    death to my progress...

    so..

    after some digging, here is what worked for me

    in my ajax call, I set the beforesend:function(xhr){

    xhr.setRequestHeader("Accept","application/json;odata=verbose");

    xhr.setRequestHeader("MaxDataServiceVersion","3.0");

    }

    apparently v3.0 is getting ready for something called json light.. and Microsoft has done this change to support it. In the future, when you do the application/json   it will return jsonlight..

    but that part is not turned on yet.

    so all the video watching on the json odata works with v2.0, but when you go to v3.0 you get a new mix.

    Happy javascript 


    Patrick

    Thursday, November 1, 2012 5:01 PM
  • A good share!

    Go go Doraemon!

    Friday, November 2, 2012 2:25 AM