3

I need to call a JSON API for a BPM engine from my asp.ner mvc web application . The API call to the BPM is constructed as follow:-

http://localhost:8080/jw/web/json/workflow/process/list?j_username=kermit&hash=9449B5ABCFA9AFDA36B801351ED3DF66&loginAs=' + username

where both the j_user & hash paramertes represents a master login username and password which are set at the BPM engine side. Currently i am calling the API using java/script at the view level from my asp.net mvc:-

$(document).ready(function () {
    var fullurl = 'http://localhost:8080/jw/web/json/workflow/package/list?j_username=kermit&hash=9449B5ABCFA9AFDA36B801351ED3DF66&loginAs=' + username ;
    $.ajax({
        type: "GET",
        url: fullurl, 

        dataType: "JSONP",
        // contentType: "application/json; charset=utf-8",
        success: function (result) {

            $.each(result.data, function (key, val) {

                // Format the text to display.
             //   var str = val.packageName + ' | ' + val.packageId;
                var str = val.packageName ;
                // Add a list item for the product.
                $('<li/>', { text: str })
                .appendTo($('#products'));

            });
        }
    });


});

But i was told that exposing both the master-login username and password and also the LoginAS username which represents the username of the login user at the asp.net mvc is not secure, AND THAT I SHOULD PERFORM THE API CALL AT THE SERVER SIDE INSTEAD OF MAKING THE API CALL FROM A JAVASCRIPT.

but my question is how i can convert my above code to receive the JSON from the mvc controller side and then pass the JSON to the view? Best Regards

1
  • 1
    Just a heads up on terminology since I was confused for a brief moment. View is usually also rendered on the server. In a MVC architechture all of M,V,C are performed on the server. "Perform call from server, and not client" would have been more precise. Commented Oct 11, 2012 at 9:04

1 Answer 1

7

You could use a WebClient to fire an HTTP request to the specified url:

public class PackagesController: Controller
{
    public ActionResult List()
    {
        using (var client = new WebClient())
        {
            var query = HttpUtility.ParseQueryString(string.Empty);
            query["j_username"] = "kermit";
            query["hash"] = "9449B5ABCFA9AFDA36B801351ED3DF66";
            query["loginAs"] = "some_username";
            var url = new UriBuilder("http://localhost:8080/jw/web/json/workflow/package/list");
            url.Query = query.ToString();
            string json = client.DownloadString(url.ToString());
            return Content(json, "application/json");
        }
    }
}

or you could use the new HttpClient introduced in .NET 4.5:

public class PackagesController : AsyncController
{
    public async Task<ActionResult> ListPackages()
    {
        using (var client = new HttpClient())
        {
            var query = HttpUtility.ParseQueryString(string.Empty);
            query["j_username"] = "kermit";
            query["hash"] = "9449B5ABCFA9AFDA36B801351ED3DF66";
            query["loginAs"] = "some_username";
            var url = new UriBuilder("http://localhost:8080/jw/web/json/workflow/package/list");
            url.Query = query.ToString();
            var response = await client.GetAsync(url.ToString());
            var result = await response.Content.ReadAsStringAsync();
            return Content(result, "application/json");
        }
    }
}

and from your javascript send an AJAX request to the aforementioned action:

<script type="text/javascript">
    $(document).ready(function () {
        $.ajax({
            url: '@Url.Action("List", "Packages")', 
            type: 'GET',
            cache: false,
            success: function (result) {
                $.each(result.data, function (key, val) {
                    var str = val.packageName;
                    $('<li/>', { text: str })
                        .appendTo($('#products'));
                });
            }
        });
    });
</script>
Sign up to request clarification or add additional context in comments.

5 Comments

thanks for the reply, it partially work . if i manually navigate to the following URL localhost:1431/Home/ListPackages i will get the Json , but the problem i think is that url: '@Url.Action("ListPackages", "Home")' inside the script is not working ,, but i do not know why?
Is this script inside your view? Or is it in a separate javascript file?
If it is in a separate javascript file you cannot use server side helpers. You should not manually construct urls. You should never do that in an ASP.NET MVC application. You could include this url for example in some DOM element as an HTML5 data-* attribute. For example you could embed it in the <body> tag: <body data-url="@Url.Action("List", "Packages")"> and then inside your separate javascript retrieve it using url: $('body').data('url').
thanks for the reply, but there is no Body tag in my Index.csthml view. shouls i create a new body tag..
There's a body tag in your _Layout. Alternatively you could add a div in your Index page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.