Ajax call WebMethod in .cs file

Topics: Customizing Orchard
Sep 2, 2014 at 8:32 PM
Edited Sep 2, 2014 at 8:34 PM
I'm trying to call a server side method from a custom module in a file called whitelist.aspx.cs using ajax but no matter what I use as the url to the .cs page I get a 404 (Not Found) error. Any ideas how to properly do this?

Javascript Code:
$(document).ready(function () {
function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
        vars[key] = value;
    });
    return vars;
}

if (getUrlVars()["url"].indexOf("http") > -1) {
    var urlArray = getUrlVars()["url"].split('/');
    //var protocol = urlArray[0];
    var transferurl = urlArray[2];
} else {
    var transferurl = getUrlVars()["url"];
}

$.ajax({
    type: "GET",
    url: "whitelist.aspx/isValidURL",
    data: {url:transferurl},
    contentType: "application/json; charset=utf-8",
    dataType: "json"
}).done(function (data) {
    if (data) {
        //Redirect to the requested url because it was a valid url in the whitelist
        setTimeout(function () { window.location.assign(transferurl); }, 5000);
    } else {
        //Don't redirect to the requested url because it wasn't a valid url in the whitelist
    }
}).fail(function () {
    //Don't redirect to the requested url because there was an error looking it up in the whitelist
});
});

C# code:
public class whitelist
{
    [WebMethod]
    public static bool isValidURL(string requestedURL)
    {
        //Create a list of strings to contain all the "valid" URLs
        var whiteList = new List<string>();
        //Add URLs to the list
        whiteList.Add("www.google.com");

        foreach (string validURL in whiteList)
        {
            if (requestedURL == validURL)
            {
                return true;
            }
        }

        return false;

    }
}
The Javascript file is under the Scripts folder and is being included in the page using Vanderlay Industries' Classy module and the .cs file is in the root of my custom module. I've tried naming the file as whitelist.cs and whitelist.aspx.cs but no dice. Thank you ahead of time for any help you can give me.
Sep 2, 2014 at 10:07 PM
Edited Sep 2, 2014 at 10:08 PM
I've since found out that I need to set up a controller and a router but am new to how MVC works and don't know how to get my controller to run the code when I get to the speedbump page. Do I still need to use an ajax call to the url specified in my Routes.cs file or can I scrap all the javascript and just use my controller and router to accomplish my goal?

The end goal is thus: I have altered TinyMce to change all inserted URLs (links) to direct to /speedbump?url="url that the user entered for the link" I then need the controller to check the url that was posted in the query string against a predefined list of "valid URLs" and if it matches any of the "valid URLs" redirect the user to the url in the query string after waiting 5 seconds. The /speedbump page is a custom content type that currently runs the following javascript code to redirect the user (doesn't actually work though).

Javascript Code:
$(document).ready(function () {
function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
        vars[key] = value;
    });
    return vars;
}

if (getUrlVars()["url"].indexOf("http") > -1) {
    var urlArray = getUrlVars()["url"].split('/');
    //var protocol = urlArray[0];
    var transferurl = urlArray[2];
} else {
    var transferurl = getUrlVars()["url"];
}

$.ajax({
    type: "POST",
    url: "speedbump",
    data: JSON.stringify({url:transferurl}),
    contentType: "application/json; charset=utf-8",
    dataType: "json"
}).done(function (data) {
    if (data.d) {
        //Redirect to the requested url because it was a valid url in the whitelist
        setTimeout(function () { window.location.assign(transferurl); }, 5000);
    } else {
        //Don't redirect to the requested url because it wasn't a valid url in the whitelist
    }
}).fail(function () {
    //Don't redirect to the requested url because there was an error looking it up in the whitelist
});
});

Controller:
public class AdminController : Controller
{
    [HttpPost]
    public bool isValidURL(string requestedURL)
    {
        //Create a list of strings to contain all the "valid" URLs
        var whiteList = new List<string>();
        //Add URLs to the list
        whiteList.Add("www.google.com");

        foreach (string validURL in whiteList)
        {
            if (requestedURL == validURL)
            {
                //Response.Redirect(requestedURL);
                return true;
            }
        }
        return false;
    }
}
Router:
public class Routes : IRouteProvider
{
    public void GetRoutes(ICollection<RouteDescriptor> routes)
    {
        foreach (var routeDescriptor in GetRoutes())
            routes.Add(routeDescriptor);
    }

    public IEnumerable<RouteDescriptor> GetRoutes()
    {
        return new[] {
            new RouteDescriptor {
                Priority = 15,
                Route = new Route(
                    "speedbump",
                    new RouteValueDictionary {
                        {"area", "Speedbump"},
                        {"controller", "Admin"},
                        {"action", "isValidURL"}
                    },
                    new RouteValueDictionary(),
                    new RouteValueDictionary {
                        {"area", "Speedbump"}
                    },
                    new MvcRouteHandler())
            }
        };
    }
}
Sep 2, 2014 at 11:12 PM
I can now reach the url in the Routes.cs file and the code in my controller successfully runs but only when I'm logged in. If I try to reach the url while logged out I get an access denied message. Is it possible to allow the url to be reached by all visitors of the site?