Dynamic JavaScript Returned By Webapi
I am using requirejs to load JavaScript for my page.  I have a webApi route that dynamically reads from a file and returns JSON using the Newtonsoft JObject.  On the client side I
Solution 1:
You want this question: Is there a way to force ASP.NET Web API to return plain text?
You don't need to create a PlainTextFormatter (I think the only benefit is automatic capturing when text/plain is requested?), you just need a helper method:
    /// <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;
    }
Then for any GetSomething method(s), you write:
    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)))
            ));
    }
Which results in a request to /myapicontroller/getmysomething1/ (assuming your route is set up to allow actions) returning:
window.SomeValue = {RandomValue1:"RandomValue1",RandomValue2:"RandomValue2",...}
Post a Comment for "Dynamic JavaScript Returned By Webapi"