404 error in calling ashx handler of Web Api - c#

I have an ImageUploadHandler.ashx handler in my WebApi Project. Source code is available here. I am trying to call my handler from my AngularJs project. Here is the code:
var serviceBase = 'http://baseDomain/';
var plupload = null;
$scope.uploadedFiles = [];
$scope.fileUpload = {
url: serviceBase + 'ImageUploadHandler.ashx',
options: {
multi_selection: true,
drop_element: "pluploadDropzone",
chunk_size: '200kb',
runtimes: 'html5,flash,silverlight,html4',
browse_button: "pluploadDropzone",
container: "pluploadContainer",
max_file_size: '3mb',
mime_types: [{ title: 'Allowed', extensions: 'jpeg, jpg, png, gif' }]
},
callbacks:
{
filesAdded: function (uploader, files) {
plupload = uploader;
for (var i = 0 ; i < files.length ; i++) {
var file = files[i];
$scope.uploadedFiles.push(file);
plupload.start();
}
}
}
}
Html:
<div id="pluploadContainer" class="uploader">
<a ng-hide="uploadedFiles.length >= 10" id="pluploadDropzone"
plupload="fileUpload.url"
plupload-options="fileUpload.options"
plupload-callbacks="fileUpload.callbacks"
class="dropzone html5Dropzone" style="width: 464px;">
<span ng-hide="uploadedFiles.length >= 10" class="instructions html5Instructions">
Drag & Drop Your Files Here!
</span>
</a>
<div class="m-images">
<ul class="images">
<li ng-repeat="file in uploadedFiles" class="image">
<div class="thumbnail">
{{ file.name }}
</div>
<a ng-click="deleteImage(file)" class="delete">×</a>
</li>
</ul>
</div>
I am getting 404 error while calling this handler, Here is the error snapshot:

This did the trick:
public void ProcessRequest(HttpContext context)
{
context.Response.ClearHeaders();
string origin = context.Request.Headers["Origin"];
context.Response.AppendHeader("Access-Control-Allow-Origin",
string.IsNullOrEmpty(origin) ? "*" : origin);
string requestHeaders = context.Request.Headers["Access-Control-Request-Headers"];
context.Response.AppendHeader("Access-Control-Allow-Headers",
string.IsNullOrEmpty(requestHeaders) ? "*" : requestHeaders);
context.Response.AppendHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
}
Plus I have to register my handler in web.config
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true">
</modules>
<handlers>
<add name="ImageUploadHandler" verb="*" path="ImageUploadHandler.ashx" type="JetAdz.WebApi.ImageUploadHandler, JetAdz.WebApi, Version=1.0.0.0, Culture=neutral" />
</handlers>
</system.webServer>

Related

Cross-Origin Request Blocked - .net Web API and JS AJAX

I'm attempting to use Ajax to capture a submit event and then send the form elements formatted as JSON to a asp.net Web API 2. I am using the latest version of FireFox. Ad blocker is disabled. I have an SSL on both origin and destination. I have followed the steps in this guide to Enable cross-origin requests.
https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api
I have tested that my form with out javascript can send to the API no problem and recieve results.
I have also tested using Postman.
I would like to capture the response from the API and show it in an alert message.
here is a screen shot of the error in the browser
https://imgur.com/a/3wM7M1Y
here is a screen shot from postman of the server response confirming it accepts all
https://imgur.com/a/1MZ9dGE
Here is my HTML
`
<!DOCTYPE html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TLogin</title>
<link rel="stylesheet" href="CSS/main.css">
<script src="JS/main.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var form = $('#login_form')[0];
form.onsubmit = function (e) {
var data = $("#login_form :input").serializeArray();
console.log(data);
$.ajax({
type: 'POST',
url: "https://api.website.org/api/users/login",
xhrFields: {
withCredentials: false
},
data: data,
processData: false,
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data);
},
error: function (xhrRequest, status, error) {
alert(JSON.stringify(xhrRequest));
}
});
return false;
}
});
</script>
</head>
<html>
<body>
<form id="login_form">
<div class="master_container">
<div id="views_container" class="clear">
<div class="view_container">
<span>Username :</span>
<input type="text" id="username" name="username">
</div>
<div class="view_container">
<span>Password :</span>
<input type="password" id="password" name="password">
</div>
<div class="view_container">
<input id="ip" type="hidden" value="myip" />
<input type="submit" id="Button_Login" value="Login" />
</div>
<div class="view_container">
</div>
</div>
</div>
</form>
</body>
</html>
`
Here is my API Controller Info
`
[EnableCors(origins: "*", headers: "*", methods: "*", exposedHeaders: "*", SupportsCredentials = false)]
public class UsersController : ApiController
{
//user login
[Route("api/Users/Login")]
[HttpPost]
public UsersSession Login(Users users)
{
UsersSession UsersSession = new UsersSession();
UsersSession.result = new Result();
try
{
if (users != null && !string.IsNullOrWhiteSpace(users.username) && !string.IsNullOrWhiteSpace(users.password))
{
var v_meta_list = new List<string>();
var v_search_results = new List<string>();
v_meta_list.Add("username=" + users.username);
v_meta_list.Add("password=" + users.password);
v_search_results = CL_db.db_search("4", v_meta_list, true);
if (v_search_results != null && v_search_results.Count > 0)
{
UsersSession.userid = v_search_results[0];
UsersSession.result.result = true;
UsersSession.result.message = "success";
}
else
{
UsersSession.result.result = false;
UsersSession.result.message = "Invalid user";
}
}
else
{
UsersSession.result.result = false;
UsersSession.result.message = "Please enter username and password";
}
}
catch (Exception ex)
{
UsersSession.result.result = false;
UsersSession.result.message = "Error occurred: " + ex.Message.ToString();
}
return UsersSession;
}
}
Here is the web.config
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="*" />
<add name="Access-Control-Allow-Methods" value="*" />
</customHeaders>
</httpProtocol>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
`
So the issue was that I had the cors stuff defined in too many locations.
The solution was simply to only have the code for the WebApiConfig.cs
I removed the code from the web.config and the controller.

Browser Connection Reset - ASP.NET MVC only when returning model with more than N elements

I am working on a ASP.NET MVC application. There are partial views, a controller, handler and a model that is iterated and its items are displayed on view.
It works fine, until I get more than 25 elements in my list. If I return 26 elements it starts showing a "The connection was reset" message in the browsers(FF and Chrome):
These are the partial views:
Iterating model items:
#foreach(ingredientsListItemModel ingredientsListItem in Model.ingredientsListItems)
{
<text>
<div id="#ingredientsListItem.ContainerDiv">
#Html.Partial("Partial/ingredientsListItem", ingredientsListItem)
</div>
</text>
}
Showing each item as a container:
#using (Ajax.BuildForm("AddElement", "Item", Model.FormId, new AjaxOptions { UpdateTargetId = Model.ContainerDiv }))
{
<div id="ingredientsListitem" class="yui3-g ingredientsListitem">
<div class="yui3-u-1-3">
<a href="#url">
<img src="#Model.ImageUrl" alt="" />
</a>
</div>
<div class="yui3-u-2-3">
<div class="itemdescription">
<a href="#url">
#MvcHtmlString.Create(Model.ItemDescription)
</a>
</div>
</div>
</div>
#Html.HiddenFor(m => m.ingredientsListId);
}
These are the controller methods to have an idea of the data:
Controller:
public ActionResult GetingredientsList()
{
if (Request.IsAjaxRequest())
{
return PartialView("Partial/ingredientsList", Handler.GetingredientsListModel(MvcApplication.ClientApplication));
}
Handler:
private static IEnumerable<ingredientsListItemModel> GetingredientsListItems(ClientApplication clientApplication)
{
//Some code...
return list.ToList();
//if this list contains more than 25 elements it starts failing and showing the Connection reset error.
}
I tried changing the web.config to include (but it didn't work):
<configuration>
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000"/>
</webServices>
</scripting>
</system.web.extensions>
</configuration>
No matter which element is in the list, it can be any data but once it is bigger than 25 items, it fails. I am thinking there could be a response size limit to be changed in some way?
in IIS? in web.config?
It seems it is a size limit problem. Well, any help will be very appreciated.

Google reCAPTACHA - hosted in IIS - Server responded with a status of 503 (Service Unavailable) - MVC5

I integrate Google reCAPTCHA in my Registration page using MVC - Ajax.
I can able to submit reCAPTACHA in my localhost. But after I deployed into the server - getting Service unavailable 503 error. I have a different key for localhost and demo.com
No changes in my code after deployed. I just updated my Google reCAPTACHA Key from config. When Form Submit action getting service unavailable error.
Here is my Google reCaptacha Key
Here is my index.cshtml page code
<form id="reg-form" class="col-sm-6 col-sm-offset-3" action="#Url.Action("Submit","Registration")" method="post" novalidate>
<div class="form-group">
<label class="control-label" for="reg-name">Enter your name:</label>
<div class="regs">
<input id="FullName" name="FullName" class="form-control" type="text" data-error-empty="Please enter your name">
<i class="fa fa-user"></i>
</div>
</div><!-- End Name input -->
<div class="form-group">
<div id='recaptcha' class="g-recaptcha" data-error-empty="The captcha field is required."
data-sitekey="publicKeyfromGooglereCAPTACHA"></div>
</div>
<p>
<button name="submit" type="submit" class="btn btn-qubico btn-block g-recaptcha"
data-error-message="Fill out all information above!" data-sending-message="Sending..." data-ok-message="Message Sent"
data-callback="onSubmit">
<i class=" fa fa-location-arrow">
</i>Submit
</button>
</p> </form>
Here is my Registration.cs Controller
[HttpPost]
[System.Web.Services.WebMethod]
public JsonResult Submit(FormCollection formcollection)
{
try
{
int status = 0;
form.FullName = formcollection["FullName"];
CaptchaResponse response = ValidateCaptcha(Request["g-recaptcha-response"]);
if (response.Success)
{
status = 1;
}
else
{
status = 0;
}
return Json(status);
}
catch (Exception ex)
{
return Json(ex.Message + ex.InnerException.Message);
}
}
[HttpPost]
/// <summary>
/// Validate Captcha
/// </summary>
/// <param name="response"></param>
/// <returns></returns>
public static CaptchaResponse ValidateCaptcha(string response)
{
string secret = System.Web.Configuration.WebConfigurationManager.AppSettings["recaptchaPrivateKey"];
var client = new WebClient();
var jsonResult = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secret, response));
return JsonConvert.DeserializeObject<CaptchaResponse>(jsonResult.ToString());
}
Here is my Model CaptchaResponse.cs -
public class CaptchaResponse
{
[JsonProperty("success")]
public bool Success
{
get;
set;
}
[JsonProperty("error-codes")]
public List<string> ErrorMessage
{
get;
set;
}
}
Here is my Jquery script
$(document).ready(function () {
$('#reg-form').submit(function () {
$.ajax({
type: "POST",
url: "Registration/Submit",
data: formInput,
dataType: "json",
success: function (data) {
console.log(JSON.stringify(data));
},
error: function (data) {
console.log(JSON.stringify(data));
}
});
}
return false;
});
});
Here is my web.config code
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="reCaptchaPublicKey" value="publicKeyfromGooglereCAPTACHA" />
<add key="reCaptchaPrivateKey" value="privateKeyfromGooglereCAPTACHA" />
Note: Application hosted in https port.
Let me know if any more details required.
This issue is fixed. I have added below lines in the config file.
<handlers>
<add name="MSCaptcha" verb="GET" path="/CaptchaImage.axd" type="MSCaptcha.captchaImageHandler, MSCaptcha"/>
</handlers>
or use the below steps to add handlers
Select your application in IIS.
Open Handler Mappings under IIS either by double click the Handler Mappings
or click "open feature" under Action
Click "Add Managed Handler" under action.
Enter "CaptchaImage.axd" without quotes in Request Path Under Type select
MSCaptcha.CaptchaImageHandler
Enter "MSCaptcha" without quotes in Name and click OK

Hosting a webService in Sharepoint

I'm loosing my mind with an issue about hosting wcf in SharePoint. I'm not able to reach my webservice, I saw on it on my SharePoint site but when I'm clicking on it I have an error message
Edit: I delete my public key to be sure that the problem doensn't come from here
So i have my ASP.NET Web Application which is called: Foo.PS2016.PSIExtension
With its iservice and Service (Very simple one):
Iservice:
namespace Foo.PS2016.PSIExtension
{
[ServiceContract]
interface IService
{
[OperationContract]
bool isAlive();
}
}
Service:
namespace Foo.PS2016.PSIExtension
{
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
internal class Service : IService
{
public bool isAlive()
{
return (true);
}
}
}
its Service.svc:
<%# ServiceHost Language="C#" Debug="true" Service="Foo.PS2016.PSIExtension.Service" %>
and its webservice:
<?xml version="1.0" encoding="utf-8"?>
<!--
-->
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5.2"/>
<httpRuntime targetFramework="4.5.2"/>
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"/>
</httpModules>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<directoryBrowse enabled="true"/>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://sfd-2016-01/sites/pwa/" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
and I have my SharePoint solution with its folder ISAPI=>PSI=>Foo.PS2016.PSIExtension.svc :
The Version, culture and PublicKey comes from a powershell command from the file: Foo.PS2016.PSIExtension.dll
So I have been stucking on this issue since this morning so if someone has some ideas to help me
So this is the result of my ajax call:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns:o="urn:schemas-microsoft-com:office:office" lang="en-us" dir="ltr">
<head><meta name="GENERATOR" content="Microsoft SharePoint" /><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><meta http-equiv="Expires" content="0" /><meta http-equiv="X-UA-Compatible" content="IE=8"/><meta name="ROBOTS" content="NOHTMLINDEX" /><title>
Error
</title><link rel="stylesheet" type="text/css" href="/_layouts/15/1033/styles/corev15.css?rev=i237P0%2BWmCDIsNnTvKWmyg%3D%3DTAG0"/>
<link rel="stylesheet" type="text/css" href="/_layouts/15/1033/styles/error.css?rev=uLsAgejtz6uU3M4tXKgEfA%3D%3DTAG0"/>
<script type="text/javascript" src="/_layouts/15/1033/initstrings.debug.js?rev=FPxEulJ9Nz3gxtb2SaxF6g%3D%3DTAG0"></script>
<script type="text/javascript" src="/_layouts/15/init.debug.js?rev=2nn1mwPjUX5aE85AUUjDGw%3D%3DTAG0"></script>
<script type="text/javascript" src="/ScriptResource.axd?d=GIJq-Z4bxUgQ1eeUBIHs5TQTn3kW6sT7yUXQTl4rpjULIbN8l-8p5XVhLDaSql7d5A-3pUW-QYv9cNcSN8liy_MdG4bV-tm3jPg_qX7_SzwnVcDWWxcD7gCBFnjOMi41nNZ1dTrbIXVUnjy2b65YO3EoqipnBU5ZsFUeYIzPrruiuztdGyeUat-m3R42Mv8a0&t=2a48f442"></script>
<script type="text/javascript" src="/_layouts/15/blank.js?rev=Y52JlQQL8Ld7e28E1u1PXw%3D%3DTAG0"></script>
<script type="text/javascript" src="/ScriptResource.axd?d=DtxdsIxZ13GzDhO3js7m9Y5qqFa6jCdy5nWUs3QtO0OiymWNuz8ei7lyf7bZCIumCWC3yWeU3nI7HsPj_4MfIjnCYUbbGjzuUKdAGAG2R016R_w2gdgT06fcxkcT6lssmCtiM7sqvDESEv9aa4lcHigN66DWM8TOlx0fEEBwiQpwSE8NNqGUPcIkkyx2wGxEmyZMGotZO6OcGHT_8EAtNg2&t=2a48f442"></script>
<script type="text/javascript">RegisterSod("require.js", "\u002f_layouts\u002f15\u002frequire.js?rev=\u00252BRRfOnYW0VaAgSoCgcIN8Q\u00253D\u00253DTAG0");</script>
<script type="text/javascript">RegisterSod("strings.js", "\u002f_layouts\u002f15\u002f1033\u002fstrings.debug.js?rev=ClRR65\u00252FJrktrUN4XIKIREQ\u00253D\u00253DTAG0");</script>
<script type="text/javascript">RegisterSod("sp.res.resx", "\u002f_layouts\u002f15\u002f1033\u002fsp.res.js?rev=MbB92HT8biYuFa\u00252B1vTMilA\u00253D\u00253DTAG0");</script>
<script type="text/javascript">RegisterSod("sp.runtime.js", "\u002f_layouts\u002f15\u002fsp.runtime.debug.js?rev=Vehk\u00252FiThFRjckdql8i15Ag\u00253D\u00253DTAG0");RegisterSodDep("sp.runtime.js", "sp.res.resx");</script>
<script type="text/javascript">RegisterSod("sp.js", "\u002f_layouts\u002f15\u002fsp.debug.js?rev=fIEkblNHoC3DmVwyA9fW7Q\u00253D\u00253DTAG0");RegisterSodDep("sp.js", "sp.runtime.js");RegisterSodDep("sp.js", "sp.ui.dialog.js");RegisterSodDep("sp.js", "sp.res.resx");</script>
<script type="text/javascript">RegisterSod("sp.init.js", "\u002f_layouts\u002f15\u002fsp.init.debug.js?rev=r7eoFYyCjoRR1v71zF6w6A\u00253D\u00253DTAG0");</script>
<script type="text/javascript">RegisterSod("sp.ui.dialog.js", "\u002f_layouts\u002f15\u002fsp.ui.dialog.debug.js?rev=JWExCHnIyo1aEflEW9vZxQ\u00253D\u00253DTAG0");RegisterSodDep("sp.ui.dialog.js", "sp.init.js");RegisterSodDep("sp.ui.dialog.js", "sp.res.resx");</script>
<script type="text/javascript">RegisterSod("core.js", "\u002f_layouts\u002f15\u002fcore.debug.js?rev=uhz\u00252B5jl6DViyR8K7N2onWQ\u00253D\u00253DTAG0");RegisterSodDep("core.js", "strings.js");</script>
<script type="text/javascript">RegisterSod("foldhyperlink.js", "\u002f_layouts\u002f15\u002ffoldhyperlink.debug.js?rev=hsjDlc\u00252BMqWuhI3IZAGCRqQ\u00253D\u00253DTAG0");</script>
<meta name="Robots" content="NOINDEX " />
<meta name="SharePointError" content="0" />
<link rel="shortcut icon" href="/_layouts/15/images/favicon.ico?rev=40" type="image/vnd.microsoft.icon" /></head>
<body id="ms-error-body" onload="if (typeof(_spBodyOnLoadWrapper) != 'undefined') _spBodyOnLoadWrapper();">
<form method="post" action="./error.aspx?ErrorText=The+type+%27Test.PS2016.PSIExtension.Service%2c+Test.PS2016.PSIExtension%2c+Version%3d1.0.0.0%2c+Culture%3dneutral%2c+PublicKeyToken%3dnull%27%2c+provided+as+the+Service+attribute+value+in+the+ServiceHost+directive%2c+or+provided+in+the+configuration+element+system.serviceModel%2fserviceHostingEnvironment%2fserviceActivations+could+not+be+found." id="aspnetForm" onsubmit="if (typeof(_spFormOnSubmitWrapper) != 'undefined') {return _spFormOnSubmitWrapper();} else {return true;}">
<div class="aspNetHidden">
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKLTMxMjY5NDA5NQ9kFgJmD2QWAgIBD2QWAgIDD2QWAgIJD2QWAgIBD2QWBAIDDw8WAh4HVmlzaWJsZWhkZAIHD2QWAgIBDw8WAh4XTGlua1RpdGxlV2hlbkZvbGRDbG9zZWQFEVRlY2huaWNhbCBEZXRhaWxzZBYIZg9kFgICAQ8PZBYCHgdvbmNsaWNrBcgBRW5zdXJlU2NyaXB0UGFyYW1zKCdmb2xkaHlwZXJsaW5rLmpzJywgJ1RvZ2dsZUZvbGRUZXh0JywgJzYzYzE2ZTE0ZDczZjQ1ODE4YTRlNmU4YjNmODY2Zjg4JywgJ2N0bDAwX1BsYWNlSG9sZGVyTWFpbl9Gb2xkTGlua19fbW9yZURldGFpbHNMaW5rJywgJ1RlY2huaWNhbCBEZXRhaWxzJywgJ1RlY2huaWNhbCBEZXRhaWxzJyk7O3JldHVybiBmYWxzZTsWAgIBDw8WAh4EVGV4dAURVGVjaG5pY2FsIERldGFpbHMWBB4EaHJlZgUBIx8CBRtQcmV2ZW50RGVmYXVsdE5hdmlnYXRpb24oKTtkAgUPDxYCHwBoZGQCCQ8PFgIfAwU0Q29ycmVsYXRpb24gSUQ6IDZiMDc1ZTllLWUxZmQtMTBhYy04N2FkLTI3M2U4NTIyYjZmYmRkAgsPDxYCHwMFI0RhdGUgYW5kIFRpbWU6IDQvMTYvMjAxOCAxOjQ5OjMyIFBNZGRk/Ntc91GhLAEgVx/VJMcHSI1WvxzG6XMahftfMlC9Lxc=" />
</div>
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['aspnetForm'];
if (!theForm) {
theForm = document.aspnetForm;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
<script src="/WebResource.axd?d=kqzbgiHYRPrIk2c8aGZXXtswgMsrN6SqxII1hyFPNd1D82NA8x9uOyjyzjXfPaUCFQZbznkKisM-JIwuoGt2n00XLarOKlQh2_rmdbXjf981&t=636160876665894255" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var g_presenceEnabled = true;
var g_wsaEnabled = false;
var g_correlationId = '6b075e9e-e1fd-10ac-87ad-273e8522b6fb';
var g_wsaQoSEnabled = false;
var g_wsaQoSDataPoints = [];
var g_wsaRUMEnabled = false;
var g_wsaLCID = 1033;
var g_wsaListTemplateId = null;
var g_wsaSiteTemplateId = 'STS#0';
var _fV4UI=true;var _spPageContextInfo = {webServerRelativeUrl: "\u002f", webAbsoluteUrl: "http:\u002f\u002fsfd-2016-01", siteAbsoluteUrl: "http:\u002f\u002fsfd-2016-01", serverRequestPath: "\u002f_layouts\u002f15\u002ferror.aspx", layoutsUrl: "_layouts\u002f15", webTitle: "Root Site Collection", webTemplate: "1", tenantAppVersion: "2395466148", isAppWeb: false, webLogoUrl: "_layouts\u002f15\u002fimages\u002fsiteicon.png", webLanguage: 1033, currentLanguage: 1033, currentUICultureName: "en-US", currentCultureName: "en-US", clientServerTimeDelta: new Date("2018-04-16T11:49:32.8917464Z") - new Date(), updateFormDigestPageLoaded: new Date("2018-04-16T11:49:32.8917464Z"), siteClientTag: "0$$16.0.4507.1000", crossDomainPhotosEnabled:false, webUIVersion:15, webPermMasks:{High:2147483647,Low:4294967295}, pagePersonalizationScope:1,userId:1073741823,userLoginName:"SHAREPOINT\\system", systemUserKey:"S-1-0-0", alertsEnabled:true, siteServerRelativeUrl: "\u002f", allowSilverlightPrompt:'True', isSiteAdmin: true};Flighting.ExpFeatures = [480215056,1880287568,1561350208,302071836,3212816,69473024,4194310,-2113396707,268502022,-872284160,1049232,-2147421952,65536,65536,2097472,917504,-2147474174,1372324107,67108882,0,0,-2147483648,2097152,0,0,32768,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32768];//]]>
</script>
<script src="/_layouts/15/blank.js?rev=Y52JlQQL8Ld7e28E1u1PXw%3D%3DTAG0" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
if (typeof(Sys) === 'undefined') throw new Error('ASP.NET Ajax client-side framework failed to load.');
//]]>
</script>
<script type="text/javascript">
//<![CDATA[
if (typeof(DeferWebFormInitCallback) == 'function') DeferWebFormInitCallback();//]]>
</script>
<div class="aspNetHidden">
<input type="hidden" name="__VIEWSTATEGENERATOR" id="__VIEWSTATEGENERATOR" value="F3F6CE2F" />
</div>
<script type="text/javascript">
//<![CDATA[
Sys.WebForms.PageRequestManager._initialize('ctl00$ScriptManager', 'aspnetForm', [], [], [], 90, 'ctl00');
//]]>
</script>
<div id="ms-error-header" class="ms-pr">
<h1 class="ms-core-pageTitle">
<div id="ctl00_PlaceHolderPageTitleInTitleArea_ErrorPageTitlePanel">
Sorry, something went wrong
</div>
</h1>
<div>
</div>
</div>
<div id="ms-error">
<div id="ms-error-top">
</div>
<div id="ms-error-content">
<div id="ms-error-error-content">
<div id="DeltaPlaceHolderMain">
<div>
<span id="ctl00_PlaceHolderMain_LabelMessage">The type 'Test.PS2016.PSIExtension.Service, Test.PS2016.PSIExtension, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null', provided as the Service attribute value in the ServiceHost directive, or provided in the configuration element system.serviceModel/serviceHostingEnvironment/serviceActivations could not be found.</span>
</div>
<div id="ctl00_PlaceHolderMain_FoldPanel" class="ms-error-detailsFold">
<div id="ctl00_PlaceHolderMain_FoldLink_foldLinkWrapper">
<div id="ctl00_PlaceHolderMain_FoldLink_foldLinkPanel" class="ms-foldHyperLink-panel" onclick="EnsureScriptParams('foldhyperlink.js', 'ToggleFoldText', '63c16e14d73f45818a4e6e8b3f866f88', 'ctl00_PlaceHolderMain_FoldLink__moreDetailsLink', 'Technical Details', 'Technical Details');;return false;">
<a id="ctl00_PlaceHolderMain_FoldLink__moreDetailsLink" class="ms-commandLink ms-floatLeft" href="#" onclick="PreventDefaultNavigation();">Technical Details</a>
<div class="ms-clear"></div>
</div>
</div><div class="ms-hide" id="63c16e14d73f45818a4e6e8b3f866f88">
<div>
<p>
<span class="ms-descriptiontext">
</span>
</p>
<p>
<span class="ms-descriptiontext">
<div id="ctl00_PlaceHolderMain_FoldLink_WSSEndUser_troubleshootingPanel">
<span id="ctl00_PlaceHolderMain_FoldLink_helptopic_WSSEndUser_troubleshooting"><a title="Troubleshoot issues with Microsoft SharePoint Foundation. - Opens in new window" href="javascript:HelpWindowKey('WSSEndUser_troubleshooting')">Troubleshoot issues with Microsoft SharePoint Foundation.</a></span>
</div>
</span>
</p>
<p>
<span id="ctl00_PlaceHolderMain_FoldLink_RequestGuidText" class="ms-metadata">Correlation ID: 6b075e9e-e1fd-10ac-87ad-273e8522b6fb</span>
</p>
<p>
<span id="ctl00_PlaceHolderMain_FoldLink_DateTimeText" class="ms-metadata">Date and Time: 4/16/2018 1:49:32 PM</span>
</p>
</div>
</div>
</div>
<div class="ms-error-techMsg">
<hr />
</div>
<script type="text/javascript">// <![CDATA[
var gearPage = document.getElementById('ms-loading-box');
if(null != gearPage)
{
gearPage.parentNode.removeChild(gearPage);
document.title = "Error";
}
function _spBodyOnLoad()
{
var intialFocus = (document.getElementById("ctl00_PlaceHolderMain_FoldLink__moreDetailsLink"));
try
{
intialFocus.focus();
}
catch(ex)
{
}
}
function _onmessage(e)
{
if (e && window.JSON)
{
var origin = e.origin;
var data = e.data;
if (window.console && window.console.log)
{
console.log("ErrorPage.OnMessage: Origin=" + origin + ", Data=" + data);
}
var requestInfo = JSON.parse(data);
if (requestInfo && (requestInfo.command == 'Ping' || requestInfo.command == 'Query'))
{
var requestGuidElem = (document.getElementById("ctl00_PlaceHolderMain_FoldLink_RequestGuidText"));
var responseInfo = {};
responseInfo.command = requestInfo.command;
responseInfo.postMessageId = requestInfo.postMessageId;
responseInfo.responseAvailable = false;
responseInfo.errorCode = -1007;
var errorMessage;
if (requestGuidElem)
{
errorMessage = requestGuidElem.textContent;
if (typeof(errorMessage) == "undefined")
{
errorMessage = requestGuidElem.innerText;
}
}
if (typeof(errorMessage) == "undefined")
{
errorMessage = "Error";
}
responseInfo.errorMessage = errorMessage;
if (window.parent && window.parent.postMessage)
{
data = JSON.stringify(responseInfo);
if (window.console && window.console.log)
{
console.log("ErrorPage.PostMessage: Origin=" + origin + ", Data=" + data);
}
window.parent.postMessage(data, origin);
}
}
}
}
if (window.addEventListener) {
window.addEventListener('message', _onmessage, false);
}
else if (window.attachEvent) {
window.attachEvent('onmessage', _onmessage);
}
// ]]>
</script>
</div>
</div>
<div id="ms-error-gobackcont" class="ms-calloutLink">
Go back to site
</div>
</div>
</div>
<script type="text/javascript">
//<![CDATA[
var g_MinimalDownload = true;var g_WebServerRelativeUrl = "/";var _spFullDownloadList = ['closeconnection', 'download', 'signout', 'xlviewer', 'wordviewer', 'wordeditor', 'powerpoint', 'powerpointframe', 'onenote', 'visiowebaccess', 'storefront', 'wopiframe', 'appredirect', 'wfstart', 'developertools'];
//]]>
</script>
</form>
</body>
</html>
Change your .svc file to:
<%# ServiceHost Language="C#" Debug="true"
Service="Foo.PS2016.PSIExtension.Service, $SharePoint.Project.AssemblyFullName$"
CodeBehind="Service.cs"
Factory="Microsoft.SharePoint.Client.Services.MultipleBaseAddressWebServiceHostFactory, Microsoft.SharePoint.Client.ServerRuntime, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
MultipleBaseAddressWebServiceHostFactory creates configuration dynamically so you can get rid of your web.config modifications and you will have your REST endpoint working out-of-the-box after deployment.
and decorate your interface methods with WebGet attribute:
[WebGet(UriTemplate = "isAlive", BodyStyle = WebMessageBodyStyle.Bare)]
and additionally (not necessarily) add BasicHttpBindingServiceMetadataExchangeEndpointAttribute to your class
As I said in comments, this tutorial goes through all actions step by step so use it!

Getting an Error while Accessing Web Service

I am working on one Console Application and in that I am using a web service but I am getting an error While accessing that service:
Client found response content type of 'text/html; charset=utf-8', but expected 'text/xml'.
The request failed with the error message:
--
<html>
<head>
<title>Runtime Error</title>
<style>
body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;}
p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
pre {font-family:"Lucida Console";font-size: .9em}
.marker {font-weight: bold; color: black;text-decoration: none;}
.version {color: gray;}
.error {margin-bottom: 10px;}
.expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
</style>
</head>
<body bgcolor="white">
<span><H1>Server Error in '/' Application.<hr width=100% size=1 color=silver></H1>
<h2> <i>Runtime Error</i> </h2></span>
<font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">
<b> Description: </b>An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed remotely (for security reasons). It could, however, be viewed by browsers running on the local server machine.
<br><br>
<b>Details:</b> To enable the details of this specific error message to be viewable on remote machines, please create a <customErrors> tag within a "web.config" configuration file located in the root directory of the current web application. This <customErrors> tag should then have its "mode" attribute set to "Off".<br><br>
<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code><pre>
<!-- Web.Config Configuration File -->
<configuration>
<system.web>
<customErrors mode="Off"/>
</system.web>
</configuration></pre></code>
</td>
</tr>
</table>
<br>
<b>Notes:</b> The current error page you are seeing can be replaced by a custom error page by modifying the "defaultRedirect" attribute of the application's <customErrors> configuration tag to point to a custom error page URL.<br><br>
<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code><pre>
<!-- Web.Config Configuration File -->
<configuration>
<system.web>
<customErrors mode="RemoteOnly" defaultRedirect="mycustompage.htm"/>
</system.web>
</configuration></pre></code>
</td>
</tr>
</table>
<br>
</body>
</html>
This is my code:
namespace ConsoleWebService
{
class MainDataService
{
static void Main(string[] args)
{
Console.WriteLine("New Account GUID="+CreateAccount("GTLDEV","New Account1"));
Console.ReadKey();
}
private static string CreateAccount(string organizationName, string accountName)
{
try
{
CrmSdk.CrmService myCrm = new CrmSdk.CrmService();
myCrm.Url = GetCrmServiceForOrganization(organizationName);
CrmSdk.CrmAuthenticationToken myToken = new CrmSdk.CrmAuthenticationToken();
myToken.AuthenticationType = 0;
myToken.OrganizationName = organizationName;
myCrm.CrmAuthenticationTokenValue = myToken;
myCrm.Credentials = System.Net.CredentialCache.DefaultCredentials;
CrmSdk.account newAccount = new CrmSdk.account();
newAccount.name = accountName;
newAccount.address1_country = "India";
newAccount.address1_city = "Mumbai";
CrmSdk.Lookup objLookup=new CrmSdk.Lookup();
objLookup.type= "account";
objLookup.Value= new Guid("A8A58DB6-5364-E111-9493-00E04C39161E");
newAccount.parentaccountid = objLookup;
CrmSdk.Lookup objLookup1 = new CrmSdk.Lookup();
objLookup1.type = "contact";
objLookup1.Value = new Guid("1EDE79DD-FC5D-E111-9493-00E04C39161E");
newAccount.primarycontactid = objLookup1;
CrmSdk.Picklist pl = new CrmSdk.Picklist();
pl.name = "address1_addresstypecode";
pl.Value = 1;
newAccount.address1_addresstypecode = pl;
Guid newAccountId = myCrm.Create(newAccount);
return newAccountId.ToString();
}
catch (System.Web.Services.Protocols.SoapException soapEx)
{
Console.WriteLine("SOAP exception: " + soapEx.Detail.InnerText + " " + soapEx.ToString());
return soapEx.Detail.InnerText + " " + soapEx.ToString();
}
catch (Exception ex)
{
Console.WriteLine("General exception: " + ex.ToString());
return "General exception: " + ex.ToString();
}
}
private static string GetCrmServiceForOrganization(string organizationName)
{
string urlResult = "";
CrmSdk.Discovery.CrmDiscoveryService myCrm = new CrmSdk.Discovery.CrmDiscoveryService();
//myCrm.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
System.Net.CredentialCache.DefaultNetworkCredentials.UserName = "kartik.patel";
System.Net.CredentialCache.DefaultNetworkCredentials.Domain = "server";
System.Net.CredentialCache.DefaultNetworkCredentials.Password = "gtl12#";
myCrm.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
CrmSdk.Discovery.RetrieveOrganizationsRequest myRequest = new CrmSdk.Discovery.RetrieveOrganizationsRequest();
CrmSdk.Discovery.RetrieveOrganizationsResponse myResponse = (CrmSdk.Discovery.RetrieveOrganizationsResponse)myCrm.Execute(myRequest);
foreach (CrmSdk.Discovery.OrganizationDetail tDetail in myResponse.OrganizationDetails)
{
Console.WriteLine("Organization = " + tDetail.OrganizationName);
if (String.Compare(tDetail.OrganizationName, organizationName, true) == 0)
{
return tDetail.CrmServiceUrl;
}
}
return urlResult;
}
}
}

Categories