Ajax POST to C# WCF WebService, 404 not found - http-status-code-404

I have a simple HTML page with javascript and an Ajax POST for calling a WCF WebService which I have made.
What the HTML page does, is to gather all the info from user input, wrap it in json and it should call the webservice.
The webservice should receive the Ajax POST, deserialize json into an object and insert it into the DB.
I have the WCF service published under my localhost IIS Server, but I get the error 404 not found. I also have the HTML page hosted in a different application, under the same website, in the same IIS localhost.
What could be the problem? I am trying to fix this for 2 days now, with no succes.
So this is my code:
Ajax post:
$.ajax({
type: 'POST',
crossDomain: true,
dataType: 'json',
url: "http://localhost/wcf_test/Service1/InsertUpdateIndividualEpxert",
data: JSON.stringify({individualExpert}),
contentType: "application/json; charset=utf-8",
success: onDataReceived,
error: onDataError
});
function onDataReceived(data)
{
console.log('Everything is good!');
}
function onDataError()
{
console.log('Not working mister!');
}
WCF Interface:
[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "InsertUpdateIndividualEpxert/{json}")]
void InsertUpdateIndividualEpxert(string json);
WCF Web.Config:
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="Service1_HttpBinding">
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="Service1_EndpointBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="Service1_ServiceBehavior">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="false" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="Service1_ServiceBehavior" name="WS_Experts.Service1">
<endpoint address=""
behaviorConfiguration="Service1_EndpointBehavior"
binding="webHttpBinding"
bindingConfiguration="Service1_HttpBinding"
contract="WS_Experts.IService1" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>

So I had just 2 problems.
In the service interface, UriTemplate should have been "InsertUpdateIndividualEpxert" and NOT "InsertUpdateIndividualEpxert/{json}"
I wrote "Epxert" instead of "Expert".
The tool I used to figure this out was Google Chrome's "PostMan"(not advertising anything, just giving full specs), which gave me the error I could understand "Endpoint not found" ... It was at that moment I knew where I messed up!
Right now I'm getting a "405 Method not allowed", but that my friends is a different ball game!
Happy coding everyone!

Related

Cross origin post request from Angular get blocked by ASP Web API

I have my post requests from angular $http getting failed on IIS, so I have made connfiguration changes to allow any header, method and origin with preflight timeout to 10 minutes. Still the preflight request fails. Any idea whats happening here?
Angular post request:
return $http({
method: 'POST',
url: Constants.BASE_URL_WEB_API + '/urlToAction',
data: JSON.stringify(postData),
headers: { 'Content-Type': 'application/json' }
});
On web.config Web API:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="*" /> <!-- GET, PUT, POST, DELETE, HEAD, OPTIONS -->
<add name="Access-Control-Max-Age" value="600"/>
<add name="Access-Control-Allow-Headers" value="*" />
</customHeaders>
</httpProtocol>
Requet summary - FF developer tool
It is not the problem of your frontend.
check API configuration, and al browser whichever you are using.
In the WebApiConfig class add the following:
public static void Register(HttpConfiguration config)
{
config.EnableCors();
config.MapHttpAttributeRoutes();
// Web API routes below
}

CORS preflighting to WebAPI2 not returning correct headers

I've been fighting a CORS issue for a few days now and I'm stuck. I've got an angular app trying to do a simple HTTP Post of Json data.
I've gone down the route described here: ASP.NET Web API - CORS Support in ASP.NET Web API 2 With a custom factory, and I've set my web.config up as:
<handlers>
<remove name="WebDAV"/>
<remove name="OPTIONSVerbHandler"/>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
My $http post call:
var serviceEndpoint = "https://mybox/ourservices/myservices/1.0.0.1/api/process";
var requestData ={'FirstName':'Nick','LastName':'Jacobs'};
$http({
method: "POST",
url: serviceEndpoint,
withCredentials: true,
data: requestData,
headers: {
'Content-Type': 'application/json',
'Accept':'application/json'
}
})
.success(function (data, status, headers, config) {
// I need to pick off the user name from the JSON that's returned.
console.log(data);
deferred.resolve(data);
})
.error(function (data, status) {
deferred.reject(data);
});
The thing is, I see the pre-flight request to the server, it's passing my origin, and asking for appropriate headers, but I get none of the CORS response headers back. If I go into the web.config and add in the allowed-methods, I do see that come back, but since I'm using withCredentials then I can't use a wild card origins response header, and I was hoping the factory described in the MSDN document above would have solved my problem.
Any ideas what I'm missing?
Thanks eveyrbody!
You need to configure CORS in web api application. There are a nuget package for CORS, basically it's an attribute in web api controller and one line configuration in web api config class something like config.EnableCors(). No need any angular configuration. Tks
MenusItemController.cs
[RoutePrefix("api/menus")]
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class MenuItemsController : ApiController
{
[Route("")]
public IHttpActionResult Post()
{
return Ok(new
{
Result = "post menus"
});
}
[Route("")]
public IHttpActionResult Get()
{
return Ok(new
{
Result = "get menus"
});
}
}
WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
config.EnableCors();
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
Nuget Packages:
Microsoft.AspNet.WebApi.Cors
Microsoft.Owin.Cors
Microsoft.AspNet.Cors
I published my app and worked fine. I didn't do anything configuration or angular request parameters. Try to GET or POST here: http://www.blocodecodigo.com.br/api/menus.

angularjs POST Image to WCF RESTful

This Question has been asked quite a lot, I have searched Google thoroughly (mostly stackoverflow), but none of the solutions worked for me.
I am trying to upload an image (base64) to my WCF Service with angularjs.
response error:
POST http://localhost:8080/Service.svc/Method 413 (Request Entity Too
Large)
The main solution on most questions is allowing a bigger request in your webconfig:
<bindings>
<basicHttpsBinding>
<binding maxBufferPoolSize="2147483647"
maxReceivedMessageSize="2147483647"
maxBufferSize="2147483647" transferMode="Streamed">
<readerQuotas
maxDepth="2147483647"
maxStringContentLength="2147483647"
maxArrayLength="2147483647"
maxBytesPerRead="2147483647"
maxNameTableCharCount="2147483647" />
</binding>
</basicHttpsBinding>
</bindings>
But this still did not work for me.
I am not sure if the issue is caused by my $http request from the app:
Base64
var a = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyNpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNS1jMDE0IDc5LjE1MTQ4MSwgMjAxMy8wMy8xMy0xMjowOToxNSAgICAgICAgIj4gPHJkZjpSRE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GB28hGzLgTbQlXvrytIedQ7sYMx7JNQ+xrcS61FFJ/Cbe7r1a6A4V04U7igdEhjEjm2UFa8KdYsT4Dsx4TPey8MYTbCu5uVgdK7YPfy3RZawBzxKvX85PybOmYnUr14DiUfDeLQsxHu5cONEuNkVOvdcSxDGPl4E+IUE4lwdwFT8lLiwPqMV3I293p4cE+EWe+lF5Za6GzmaSF1BIILYA1rBLU+gQEAoUPHhLSX/bswDDYdMtyftQdMeaNEmaXgCSoxkvEYPZlhDGO6w4oe7tYp4pCoFjeNdSzpRsZkJfUFIGUVPvax1g7QIggTXzQl4mUpW0R02f5UzvmqBmP3znOBov0yIQB5rAFg/DVXOe2mGcKRMGm2Q6DZYwBG7McWFQXRIAie485SITFt7HGmk+i6KIcJ+iCio8aagKgsMyUSHEnqINaxyskjg9Fce8I+IWkc6HVaIn7WVlFZHRM7Ws69VBACRQvuZkFoQT+AltmqffWs+zy1u85CD1eqPLg3eAcR8fMj0lXmvK03RzbiNtqiE/2QilRnWwWuLpxpMM5wucVp/xTIGiipuZ6Wt4u7bO6C9XnxH+J8AAr8HYPGJEAIIAAAAASUVORK5CYII=';
$http
$http({
method: 'POST',
url: ' http://localhost:8080/Service.svc/Method',
data: "message=" + a,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data) {
console.log(data);
})
.error(function(data) {
console.log("failure");
})
};
This is the best solution I have found and it works perfectly.
From Client side (Angularjs), I followed a uncorkedstudios.com article, it explains how to upload an image using Multipart/form-data.
Then for Server side see this question stackoverflow.com/questions/1354749/wcf-service-to-accept-a-post-encoded-multipart-form-data It explains the sever side by using stream when receiving a request from your client.
Your Method parameter will probably look like this: {System.ServiceModel.Dispatcher.StreamFormatter.MessageBodyStream}
For this I used a class found on multipartparser.codeplex.com.
The coding below with the class should be enough to figure out.
public string Upload(Stream stream)
{
MultipartParser parser = new MultipartParser(stream);
if(parser.Success)
{
// Save the file
SaveFile(parser.Filename, parser.ContentType, parser.FileContents);
}
else
{
throw new WebException(System.Net.HttpStatusCode.UnsupportedMediaType, "The posted file was not recognised.");
}
}
Hope it helps.

$http.get of json file always returns 404

I want to add to my application a configuration JSON file.
I've added it to my project and tried to get it using $http.get:
$http.get('http://localhost/myProject/content.json').success(function (data) {
// Do stuff...
}).error((data, status, headers, config) => {
// Failure...
});
The problem is that every time I get an error 404.
This is an issue with your web server mime type configuration - it has none for json, probably.
Try renaming the file extension to .txt or .html and it should work.
You can also add the mime type extension to the server. For IIS express, it's web.config. For example:
<staticContent>
<remove fileExtension=".json" />
<mimeMap fileExtension=".json" mimeType="application/json" />
</staticContent>
put content.json file sibling to index.html and use this:
$http.get('content.json').success(function (data) {
// Do stuff...
}).error((data, status, headers, config) => {
// Failure...
});
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
**<system.webServer>
<staticContent>
<mimeMap fileExtension=".json" mimeType="application/json" />
</staticContent>
</system.webServer>**
</configuration>
This works fine.. as what Erez A. Korn has said.
In angular 4 store .json file into your root folder of project. all Json file store in same folder.

WEB API AngularJS Google+Login CORS not allowed

i am currently using WEB API 2 and AngularJS.
(livermorium:1234 = where my web api is running from.)
I simply want to use Google+ and Facebook-Login, but i am not able to give access to external urls like http:www.google.de for authentication.
This is my angularJS request:
$http.get('http://Livermorium:1234/api/Account/ExternalLogins?returnUrl=/&generateState=true')
.success(function (data, status, headers, config) {
$http.get('https://www.google.de')
.success(function (data) {
$log.log('-- successfull Google retrievement');
$log.log(data);
})
})
And in my WEB API "WebApiConfig.cs" i even allowed every url cors enabled:
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
But it keeps telling me:
XMLHttpRequest cannot load https://www.google.de/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://livermorium:1234' is therefore not allowed access.
I even added customHeaders to my webconfig. Without success.
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS, PUT, DELETE" />
<add name="Access-Control-Allow-Headers" value="*" />
</customHeaders>
</httpProtocol>
Has anyone a working example or an idea why my request keeps being denied?
I am using the owin middleware, too. So i had to do some changes:
"WebApiConfig.cs" old:
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
"WebApiConfig.cs" new:
config.EnableCors();
"startup.cs" i added this line:
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
So it looks like this:
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
ConfigureOAuth(app);
WebApiConfig.Register(config);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(config);
}
Resource: http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/
Thank you very much
if you set config.EnableCors(cors) is't necessary the customHeader in web.config.
remove all'customHeader from your web.config.
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS, PUT, DELETE" />
<add name="Access-Control-Allow-Headers" value="*" />
i had the same problem, and I solved this way.

Resources