wcf service working with 'GET' and 500 error with 'POST' - wcf

I have a wcf service that it's working well if i am using get but
when i use post it's showing
System.ServiceModel.ServiceActivationException status 500
any ideas whats the error??
here is the code
function Login(e) {
debugger;
e.preventDefault();
//getting mail
var loginmail =
$("[id$='txtLoginEmail']").val();
//getting password
var loginpassword =
$("[id$='txtLoginPassword']").val();
//getting remember me checkbox
var checked =
($("[id$='chkRememberme']").is(':checked'));
var proxy = new _AppProxy('MemberService/Login', '', 'xml', 'POST', '', { mail: loginmail, password:
loginpassword, rememberMe: checked });
proxy.Invoke();
};
[OperationContract]
[WebInvoke(ResponseFormat =
WebMessageFormat.Xml,Method="POST")]
public string Login(string mail , string password ,
bool rememberMe)
{
}
<system.serviceModel>
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint
name=""
helpEnabled="true"
automaticFormatSelectionEnabled="true" />
</webHttpEndpoint>
</standardEndpoints>
serviceHostingEnvironment
aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" >
</serviceHostingEnvironment>
</system.serviceModel>

Can be that you miss the .svc ending in your URI to the WebService. If MemberService is the name of the service and Login is the name of the Method,
MemberService.svc/Login

Related

How to configure axios to request WebAPI with auth?

I have a local ASP.Net FrameWork WebAPI server with the following controller:
public class ValuesController : ApiController
{
// GET api/values
[AuthorizationFilter]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
}
I created an AuthorizationFilter attribute to handle authorization (only for GET with no id action):
public class AuthorizationFilter : AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext ctx)
{
if(ctx.Request.Headers.Authorization == null)
{
ctx.Response = ctx.Request.CreateResponse(System.Net.HttpStatusCode.Unauthorized);
} else
{
string authenticationString = ctx.Request.Headers.Authorization.Parameter;
string decodedAuthString = Encoding.UTF8.GetString(Convert.FromBase64String(authenticationString));
string username = decodedAuthString.Split(':')[0];
string password = decodedAuthString.Split(':')[1];
// assume that I have checked credentials from DB
if (username=="admin" && password=="root")
{
// authorized...
} else
{
ctx.Response = actionContext.Request.CreateResponse(System.Net.HttpStatusCode.Unauthorized);
}
}
}
}
Also, I modified Web.config to allow CORS:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
...
</system.webServer>
I ran the server and tried to get /api/values/1 from the browser, and it worked.
I then tried to access the action that requires authorization: /api/values :
I used Insomnia to send requests and test CORS. First I tried the action that doesn't require authorization:
Then I tried the action with authorization:
Then I tried the same action but after adding the authentication username and password, and that worked out fine:
After this point, I knew my webapi is configured correctly, so I tried to pull data from a React app using axios:
const api = axios.create({
baseURL: "http://localhost:50511/api",
});
const response = await api.get("/values/1");
console.log(response.data); // works fine: I get "value" as expected
And now, the final step, to configure axios to request the action that requires authentication:
const api2 = axios.create({
baseURL: "http://localhost:50511/api",
auth : {
username: "admin",
password: "root"
}
});
const response = await api2.get("/values"); // causes a network exception
The reported error is strange, since it talks about CORS. I don't get it. If there shall be an error, it can imagine it being an error related to authorization. Not CORS. Not after being able to use axios to pull data from the action that has no authentication filter.
I examined the request header to make sure that it was configured with the correct Authorization parameter:
I also tried to use axios in different ways:
const response1 = await axios.get("http://localhost:50511/api/values",{
auth: {
username: "admin",
password: "root"
}
});
const response2 = await axios.get("http://localhost:50511/api/values",{
headers: {
Authorization: "Basic " + btoa("admin:root"),
}
});
Both of these attempts did not work.
Then I tried again, but this time passing an empty object as the second parameter to the axios call:
const response3 = await axios.get("http://localhost:50511/api/values", {}, {
auth: {
username: "admin",
password: "root"
}
});
const response4 = await axios.get("http://localhost:50511/api/values", {}, {
headers: {
Authorization: "Basic " + btoa("admin:root"),
}
});
Again, none of these attempts worked. What am I don't wrong?

ajax error 500 & Internal Server Error in MVC

I used ajax method to call the controller and fetch the data and convert it to json or list and set a jquery DataTable. With 1000 records it's working fine, but when I fetch more than 5000 records, ajax method gives me:
500 Internal server error
Here is my code:
$('#btnAllData').click(function () {
$.ajax({
url: 'PartMaster/GridLoad',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (Result) {
debugger;
var pageload = Result.split('|');
var status = (pageload[0])
if (status == "ERROR") {
Error(pageload[1]);
}
else {
var Partdetails = (pageload[0]);
//var LocDetails = JSON.parse(pageload[2]);
}
//gridDetails(status1);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
check how much time your database is taking to returning data.
Set length of web response ( You can adjust the JSON response size in the web.config with ).
<configuration>
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="1000000" />
</webServices>
</scripting>
</system.web.extensions>
</configuration>

asp.net core redirect http traffic to https issue

I have just installed an ssl certificate on my host, and thought I would redirect all http traffic to https. I found that there is a new package for helping with it in .net core.
The problem is that it doesn't work for me and I can't figure out why. When I try to navigate to http://mysite.co.uk to test the redirection it fails with a message saying
The page isn't redirecting properly
Firefox has detected that the server is redirecting the request for this address in a way that will never complete.
This problem can sometimes be caused by disabling or refusing to accept cookies.
Here is my stratup.cs:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Playabout.Data;
using Playabout.Models;
using Playabout.Services;
using Microsoft.AspNetCore.Identity;
using System.Security.Claims;
using Microsoft.AspNetCore.Localization;
using Microsoft.Net.Http.Headers;
using System.Globalization;
using Sakura.AspNetCore.Mvc;
using Microsoft.AspNetCore.ResponseCompression;
using System.IO.Compression;
using System.Linq;
using Microsoft.AspNetCore.Rewrite;
using System.Net;
namespace Playabout
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsDevelopment())
{
// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
//builder.AddUserSecrets<Startup>();
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>(
config =>
{
config.SignIn.RequireConfirmedEmail = true;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.Configure<GzipCompressionProviderOptions>
(options => options.Level = CompressionLevel.Optimal);
services.AddResponseCompression(options =>
{
options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(new[]
{
"text/plain",
"text/css",
"application/javascript",
"text/html",
"application/xml",
"text/xml",
"application/json",
"text/json",
// Custom
"text/javascript",
"image/svg+xml"
});
options.Providers.Add<GzipCompressionProvider>();
});
services.AddMvc();
// Add application services.
services.Configure<SmtpConfig>(optionsSetup =>
{
//get from config.json file
optionsSetup.EmailDisplayName = Configuration["SMTP:DisplayName"];
optionsSetup.SmtpPassworrd = Configuration["SMTP:Password"];
optionsSetup.SmtpUserEmail = Configuration["SMTP:Email"];
optionsSetup.SmtpHost = Configuration["SMTP:Host"];
optionsSetup.SmtpPort = Convert.ToInt32(Configuration["SMTP:Port"]);
});
services.Configure<RecaptchaConfig>(optionsSetup =>
{
//get from config.json file
optionsSetup.RecaptchaPublicKey = Configuration["Recaptcha:PublicKey"];
optionsSetup.RecaptchaPrivateKey = Configuration["Recaptcha:PrivateKey"];
});
// Add default bootstrap-styled pager implementation
services.AddBootstrapPagerGenerator(options =>
{
// Use default pager options.
options.ConfigureDefault();
});
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
services.AddSession();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public async void Configure(IApplicationBuilder app, IHostingEnvironment env,
ILoggerFactory loggerFactory, IServiceProvider serviceProvider, ApplicationDbContext context)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
var supportedCultures = new[]
{
new CultureInfo("en-GB"),
};
app.UseRequestLocalization(new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture("en-GB"),
SupportedCultures = supportedCultures,
SupportedUICultures = supportedCultures
});
app.UseRewriter(new RewriteOptions()
.AddRedirectToHttps());
app.UseResponseCompression();
app.UseStaticFiles(new StaticFileOptions
{
OnPrepareResponse = ctx =>
{
const int durationInSeconds = 60 * 60 * 730;
ctx.Context.Response.Headers[HeaderNames.CacheControl] =
"public,max-age=" + durationInSeconds;
}
});
app.UseSession();
app.UseIdentity();
// Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715
app.UseFacebookAuthentication(new FacebookOptions()
{
AppId = Configuration["Authentication:Facebook:AppId"],
AppSecret = Configuration["Authentication:Facebook:AppSecret"]
});
app.UseGoogleAuthentication(new GoogleOptions()
{
ClientId = Configuration["Authentication:Google:ClientId"],
ClientSecret = Configuration["Authentication:Google:ClientSecret"]
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
try
{
await CreateRoles(context, serviceProvider);
}
catch (Exception)
{ }
}
private async Task CreateRoles(ApplicationDbContext context, IServiceProvider serviceProvider)
{
var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
// Create a list of roles with both name and normalised name attributes
List<IdentityRole> roles = new List<IdentityRole>
{
new IdentityRole { Name = "Admin", NormalizedName = "ADMIN" },
new IdentityRole { Name = "Member", NormalizedName = "MEMBER" },
new IdentityRole { Name = "Moderator", NormalizedName = "MODERATOR" }
};
// Check if the role already exists
foreach (var role in roles)
{
var roleExist = await RoleManager.RoleExistsAsync(role.Name);
if (!roleExist)
{ // Add it if it doesn't
context.Roles.Add(role);
context.SaveChanges();
}
}
var user = await userManager.FindByEmailAsync("markperry.uk#gmail.com");
if (user != null)
{
var gotRoles = userManager.GetRolesAsync(user);
if (!gotRoles.Equals("Admin"))
{
await userManager.AddToRoleAsync(user, "Admin");
}
}
else if (user == null)
{
var nuser = new ApplicationUser
{
FirstName = Configuration["AppSettings:Admin:FirstName"],
LastName = Configuration["AppSettings:Admin:LastName"],
PhoneNumber = Configuration["AppSettings:Admin:PhoneNumber"],
UserName = Configuration["AppSettings:Admin:UserName"],
Email = Configuration["AppSettings:Admin:Email"],
JoinDate = DateTime.Now,
EmailConfirmed = true,
PhoneNumberConfirmed = true
};
var result = await userManager.CreateAsync(nuser, Configuration["AppSettings:Admin:Password"]);
if (result.Succeeded)
{
await userManager.AddClaimAsync(nuser, new Claim("GivenName", nuser.FirstName));
await userManager.AddClaimAsync(nuser, new Claim("Surname", nuser.LastName));
await userManager.AddToRoleAsync(nuser, "Admin");
}
}
}
}
}
The snippet I added to configure is:
app.UseRewriter(new RewriteOptions()
.AddRedirectToHttps());
which uses Microsoft.AspNetCore.Rewrite;
I have just used chrome to inspect, and that shows repeated redirects, and fails due to "ERR_TOO_MANY_REDIRECTS" so something is causing a loop.
Is there a way to check if the request is already "https", or is there another way I can do things?
After spending the whole day trying to sort this out, adding [RequireHttps] attributes, trying a variety of snippets I found googling the issue, trying to pass headers... In the end I resorted to something I tried earlier that hadn't seemed to have worked. I edited the web.config file that is on the server (I don't know how to do it at publish) adding the following:
<system.webServer>
<rewrite>
<rules>
<rule name="HTTP/S to HTTPS Redirect" enabled="true" stopProcessing="true">
<match url="(.*)" />
<conditions logicalGrouping="MatchAny">
<add input="{SERVER_PORT_SECURE}" pattern="^0$" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
</rule>
</rules>
</rewrite>
</system.webServer>
Taken from a comment here: https://github.com/aspnet/KestrelHttpServer/issues/916
From what I've read, its to do with Kestrel, I'm not entirely sure what though :D but it works! It's going to be annoying to have to change this every publish, so tomorrow I'll try and figure out how this can be done for me each time.
I was able to solve a similar issue with the following:
if (env.IsProduction())
{
app.UseRewriter(new RewriteOptions().AddRedirectToHttpsPermanent());
}

WCF service and oauth + jQuery ajax call

I was trying to implement oauth authentication in my WCF service. I am doing the service call from jQuery ajax. I have tried the following code in CORS enabled service with POST verb. But here I am getting pa["oauth_consumer_key"] as always null. Please see the code and help me to find out the issue.
Using POST and CORS
jQuery ajax call:-
function logClick() {
var sEmail = $('#username').val();
var sPassword = $('#password').val();
var key = "test";
var oauth_signature = "xxxxxxx";
var timestamp = (new Date()).getTime();
var nonce = Math.random();
var auth_header = 'OAuth oauth_nonce="' + nonce + '"' +
', oauth_signature_method="HMAC-SHA1"' +
', oauth_timestamp="' + timestamp + '"' +
', oauth_consumer_key="' + key + '"' +
', oauth_signature="' + oauth_signature + '"' +
', oauth_version="1.0"';
var userData = '{"email":"' + sEmail + '","password":"' + sPassword + '"}';
$.support.cors = true;
$.ajax({
data: userData,
type: "POST",
dataType: "json",
contentType: "application/json;charset=utf-8",
url: "http://mydomain/MyAppService.svc/UserValidation",
beforeSend : function(xhr, settings) {
$.extend(settings, { headers : { "Authorization": auth_header } });
},
success: function (msg) {
alert("success");
},
error: function () {
alert("Network error");
}
});
}
WCF service code
[OperationContract]
[WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped, Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "UserValidation")]
int UserValidation(string email,string password);
public int UserValidation(string email, string password)
{
if (Authenticate(WebOperationContext.Current.IncomingRequest))
{
//my code
return 1;
}
else
{
return 0;
}
}
private static bool Authenticate(IncomingWebRequestContext context)
{
bool Authenticated = false;
string normalizedUrl;
string normalizedRequestParameters;
NameValueCollection pa = context.Headers;
//NameValueCollection pa = context.UriTemplateMatch.QueryParameters;// tried this also
if (pa != null && pa["oauth_consumer_key"] != null) // pa["oauth_consumer_key"] is always null
{
// to get uri without oauth parameters
string uri = context.UriTemplateMatch.RequestUri.OriginalString.Replace
(context.UriTemplateMatch.RequestUri.Query, "");
string consumersecret = "suryabhai";
OAuthBase oauth = new OAuthBase();
string hash = oauth.GenerateSignature(
new Uri(uri),
pa["oauth_consumer_key"],
consumersecret,
null, // totken
null, //token secret
"GET",
pa["oauth_timestamp"],
pa["oauth_nonce"],
out normalizedUrl,
out normalizedRequestParameters
);
Authenticated = pa["oauth_signature"] == hash;
}
return Authenticated;
}
I did the same aouth authentication in GET and JSONP . Following is the code. Here the authentication is working, but I am not getting the result even though the service return data. ( entering to error block in jQuery ajax call)
GET and JSONP
jQuery ajax call:-
function getData() {
$.ajax({
url: "http://mydomain/MyAppService.svc/GetData/328?oauth_consumer_key=test&oauth_nonce=10a33ed37b549301644b23b93fc1f1c5&oauth_signature=AMTsweMaWeN7kGnSwoAW44WKUuM=&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1289976718&oauth_version=1.0?callback=?",
type: "GET",
crossDomain: true,
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
processdata: true,
success: function (msg) {
alert("success");
},
error: function error(response) {
alert(" Network Error"); // always entering to this block
}
});
WCF service :-
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "GetData/{ParentID}")]
List<Parent> GetData(string ParentID);
public List<Parent> GetData(string ParentID)
{
List<Parent> ParentList = new List<Parent>();
if (Authenticate(WebOperationContext.Current.IncomingRequest)) // it is working
{
//my code
return ParentList ; // result is getting, but on client it is going to error block of jQUery ajax call
}
else
{
return ParentList ;
}
}
private static bool Authenticate(IncomingWebRequestContext context)
{
bool Authenticated = false;
string normalizedUrl;
string normalizedRequestParameters;
NameValueCollection pa = context.UriTemplateMatch.QueryParameters;
if (pa != null && pa["oauth_consumer_key"] != null)
{
// to get uri without oauth parameters
string uri = context.UriTemplateMatch.RequestUri.OriginalString.Replace
(context.UriTemplateMatch.RequestUri.Query, "");
string consumersecret = "suryabhai";
OAuthBase oauth = new OAuthBase();
string hash = oauth.GenerateSignature(
new Uri(uri),
pa["oauth_consumer_key"],
consumersecret,
null, // totken
null, //token secret
"GET",
pa["oauth_timestamp"],
pa["oauth_nonce"],
out normalizedUrl,
out normalizedRequestParameters
);
Authenticated = pa["oauth_signature"] == hash;
}
return Authenticated;
}
Web.config:-
<?xml version="1.0"?>
<configuration>
<system.web>
<authentication mode="None" />
<httpRuntime maxRequestLength="2147483647"/>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true"/>
<services>
<service name="DataAppAppService.MyAppService">
<endpoint address="" behaviorConfiguration="webHttpBehavior" binding="webHttpBinding" bindingConfiguration="WebHttpBindingWithJsonP" contract=DataAppAppService.IMyAppService" />
</service>
</services>
<bindings>
<webHttpBinding>
<binding name="WebHttpBindingWithJsonP" crossDomainScriptAccessEnabled="true" maxReceivedMessageSize="2147483647"
maxBufferSize="2147483647" transferMode="Streamed"
>
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="webHttpBehavior">
<webHttp helpEnabled="true" />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceThrottling maxConcurrentCalls="30" maxConcurrentInstances="30" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<directoryBrowse enabled="true" />
</system.webServer>
</configuration>
I was able to solve the "Using POST and CORS" issue. I have added the Authorization header into "Access-Control-Allow-Headers" and it solved the issue.
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept");
Is there any way to generate oauth_signature from javascript. Now I am hard coding the value, but as the timestamp and oauth_nonce changing each time, I am getting different signature. SO I need to pass the correct signature through the ajax request rather than giving hard coding value. Please give a suggestion.
But still I have issue with Get and JSONP and oAuth. Any thoughts?
Thanks.
"But still I have issue with Get and JSONP and oAuth. Any thoughts?" --> I could solve this issue using GET method with CORS. Here is my code.
$.support.cors = true;
$.ajax({
type: "GET",
dataType: "json",
contentType: "application/json;charset=utf-8",
url: "http://mydomain:89/MyAppAppService.svc/GetFolders",
beforeSend: function (xhr) {
var username = "test";
var password = "testpwd";
xhr.setRequestHeader("Authorization", "Basic " + $.base64('encode', username + ':' + password));
},
success: function (msg) {
alert("Success");
},
error: function (jqXHR, status, message) {
alert(jqXHR.responseText);
alert(status + " " + message);
}
});
Thanks.

jQuery Ajax call returning null from WCF RIA REST service

I have created a WCF REST .NET 4 service and deployed it to a local IIS 7.
If I use Fiddler and use the request builder, I am able to call the service and see the data been returned OK. If I try hitting the same REST location in the browser, JSON is not been returned but it looks like XML.
My service looks like this:
[OperationContract]
[WebGet(UriTemplate = "/{id}/details.json",
ResponseFormat=WebMessageFormat.Json)]
public SampleItem Get(string id)
{
return new SampleItem{ Id=1, StringValue="value from string"};
}
My web.config file has only a slight change:
<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true" defaultOutgoingResponseFormat="Json"/>
I am trying to call the service using jQuery like this:
$(document).ready(function () {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "http://wcf-rest/service1/1/details.json",
dataType: "json",
success: function (data) { alert(data); },
error: function (e) { alert("error"); }
});
}); // end .ready
However, null is being returned every time. What do I need to change?
I've been using jQuery and Ajax extensively with a JSON datatype, and I believe you need to change data to data.d. See my example below.
function getMakes() {
$.ajax({
type: "POST",
url: "../../WebService_VehicleAssignment.asmx/getAllVehicleMakes",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var response = msg.d;
$('#output').empty();
$.each(response, function (vehicle, vehicle) {
$('#output').append(new Option(vehicle.Make, vehicle.Id));
});
},
failure: function (msg) {
alert('failure');
}
});
}<br />
I use Firebug to debug this stuff. I can see exactly what's getting posted to the web service and what is coming back. And if the web service is complaining, what it's complaining about.
Read about why the .d is necessary in A breaking change between versions of ASP.NET AJAX. In short, I believe it is a wrapper so that returned data is treated as a string rather than being returned and executed if it is raw literal JavaScript code.