webapi返回的动态JavaScript

时间:2013-01-23 23:46:10

标签: javascript asp.net-web-api

我正在使用requirejs为我的页面加载JavaScript。我有一个webApi路由,它从文件中动态读取并使用Newtonsoft JObject返回JSON。在客户端,我然后获取结果并将其分配给本地JavaScript变量。

  

define(['jquery'],function($){

function dynoFile() {
    $.get('/api/resources/dynofile', function (results) {
        myNamespace.dynoFile = results;
    });
}

return new dynoFile(); });

此示例确实有效,但是它会导致其他希望myNamespace.dynoFile存在的JavaScript文件出现问题。由于这个文件加载得很好,其他文件不会等待$ .get完成。

是否可以让web api方法返回JavaScript并让浏览器将其识别为JavaScript而不仅仅是文本?我试图在web api中设置响应头,并以各种方式返回生成的脚本。

这可能吗?

更新

为了更详细一点,我使用我的Web API处理我的资源文件并将JSON返回给客户端,因为它是一个单页面应用程序。我希望从我的Web API返回JavaScript,我可以使用RequireJS加载。我现在以JSON的身份工作,并认为我会分享我拥有的东西。

这是我的WebApi方法,它读取资源文件并将其作为JSON返回:

public JObject Get()
{
    var data = new JObject();

    var type = typeof(Translations);
    var properties = type.GetProperties();

    foreach (var property in properties)
    {
        if (property.Name != "ResourceManager" && property.Name != "Culture")
        {
            data.Add( property.Name, property.GetValue(type, null).ToString());
        }
    }

    HttpContext.Current.Response.Headers.Add("Content-Type", "application/json");

    return data;
}

这是我的translations.js文件:

define(['jquery', 'underscore'], function ($) {

    function translations() {
    }

    _.extend(translations.prototype, {
        target: '/api/resources/translations',

        getTranslations: function () {
            return $.ajax({
                url: 'api/resources/translations',
                type: 'GET',
                dataType: 'json'
            });
        }
    });

    return (translations);
});

由于我的其他几个文件依赖于现有的翻译,我需要在main.js中嵌套2个RequireJS语句:

requirejs(['application/translations', 'whatever other resources that can load that don't depend on translations'], function () {
    var trans = new translations();

    trans.getTranslations()
        .done(function (result) {
            // set translations into a variable, we chose it to be part of the global namespace
            window.Translations = result;

            // load remaining dependencies that require translations to exist
            requirejs(['myotherjsfiles', 'blahblah', function () {
                // you get the idea...
            });
        });
});

这允许我的翻译首先加载(使用任何非依赖文件,如bootstrap,jquery等),然后加载我所有的依赖JavaScript文件。我还针对RequireJs优化方法对此进行了测试,并且能够解决嵌套需求。希望这有助于其他人了解如何将翻译下载到客户端和/或如何使用RequireJS加载动态模块。

如果有人知道如何让WebApi返回JavaScript,我很乐意听到它!

干杯!

1 个答案:

答案 0 :(得分:4)

你想要这个问题: Is there a way to force ASP.NET Web API to return plain text?

您不需要创建PlainTextFormatter(我认为唯一的好处是在请求text/plain时自动捕获?),您只需要一个辅助方法:

    /// <summary>
    /// Generate raw content from the given string output.
    /// <para>See https://stackoverflow.com/a/13028027/1037948 and https://stackoverflow.com/a/11582207/1037948 </para>
    /// </summary>
    /// <param name="responseBody"></param>
    /// <param name="mediaType"></param>
    /// <returns></returns>
    private HttpResponseMessage getRawResponse(string responseBody, string mediaType = "text/plain") {

        var response = Request.CreateResponse(HttpStatusCode.OK);
        response.Content = new StringContent(responseBody, Encoding.UTF8, mediaType);
        return response;
    }

然后对于任何GetSomething方法,你写:

    public object GetMySomething1() {

        return getRawResponse(string.Format(@"window.SomeValue = {{{0}}}",
                            string.Join(",",
                                        Enum.GetValues(typeof(RandomEnum)).Cast<RandomEnum>().Select(o => string.Format("{0}:\"{1}\"", o, o)))
            ));
    }

这导致请求/myapicontroller/getmysomething1/(假设您的路线设置为允许操作)返回:

window.SomeValue = {RandomValue1:"RandomValue1",RandomValue2:"RandomValue2",...}
相关问题