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
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!
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>
I have successfully written a MVC4 webapi that takes CompanyID, name and posts it to DB. I need to change it in such a way that the user can enter multiple values for CompanyID with their Names and Save it to DB in one shot. How can I do that? Here's my code
--Index.cshtml
<div id="body">
<section class="featured">
<div class="content-wrapper">
<hgroup class="title">
<h1>Welcome Web API!</h1>
</hgroup>
</div>
</section>
<section class="content-wrapper main-content clear-fix">
<p>
For API documentation: #Html.ActionLink("API", "Index", "Help", new { area = "" }, null)
</p>
<p>
Update/Insert Company info: Click Here!
</p>
</section>
</div>
--Companies.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<script>
var overrides = Array();
function parseform(button) {
var CompanyID = $("#CompanyID").val();
var CompanyName = $("#CompanyName").val();
var lst = {
CompanyID: CompanyID,
CompanyName: CompanyName
}
if (button.attr('value') === "POST") {
console.log("posting : " + lst.toString());
postdata(lst);
} else {
console.log("ERROR");
}
}
function postdata(lst) {
$("#response").text("Posted");
$.ajax({
type: "POST",
dataType: "json",
url: "api/Company/",
data: lst,
xhrFields: {
withCredentials: true
},
success: function (data, status, xhr) {
console.log(status);
$("#response").text(status)
},
error: function (xhr, status, error) {
console.log(xhr.responseText);
var json = jQuery.parseJSON(xhr.responseText);
console.log(json);
$("#response").text(status)
alert(json.Message);
}
});
}
$(document).ready(function () {
$('input:button').click(function () {
parseform($(this));
});
});
</script>
<div id="form">
<label for="CompanyID">CompanyID:</label><input type="text" id="CompanyID" /><br />
<label for="CompanyName">CompanyName:</label><input type="text" id="CompanyName" /><br />
<input type="button" id="Post" value="POST"/>
</div>
<div id="response">
</div>
</body>
</html
In CompaniesController, I have written a call to stored procedure for the POST method to save one record at a time.
How can I Post many rows at a time & what changes should I do to html file.
Thanks
R
How did you declared your variables in your Model. For operating multivalued types, try something like this:
private ICollection<string> _variable;
public ICollection<string> VariableName
{
get
{
if (_variable == null)
{
return new Collection<string> {""};
}
else
{
return _variable;
}
}
set { _variable = value; }
}