Search code examples
c#asp.net-mvcasp.net-web-apiasp.net-mvc-routing

ASP.Net Web API Http routing and non JSON responses


I want to mimic behaviour of existing web service. Here is a very simplified example showing what I want to achieve.

I use ASP.Net Web API routing: it's quite simple to configure routes with it.

Requirements, part 1: query:

GET whatever.../Person/1

shall return JSON:

Content-Type: application/json; charset=utf-8
{"id":1,"name":"Mike"}

That's piece of cake:

public class Person
{
    public int ID { get; set; }
    public string Name { get; set; }
}

// In ApiController
[HttpGet]
[Route("Person/{id}")]
public Person GetPerson(int id)
{
    return new Person
    {
        ID = id,
        Name = "Mike"
    };
}

Requirements, part 2: query:

GET whatever.../Person/1?callback=functionName

shall return javascript:

Content-Type: text/plain; charset=utf-8
functionName({"id":1,"name":"Mike"});

Any ideas how to achieve this (part 2)?


Solution

  • The ApiController would need to be modified to satisfy the desired behavior

    Simple example based on provided code

    //GET whatever.../Person/1
    //GET whatever.../Person/1?callback=functionName
    [HttpGet]
    [Route("Person/{id:int}")]
    public IHttpActionResult GetPerson(int id, string callback = null) {
        var person = new Person {
            ID = id,
            Name = "Mike"
        };
    
        if (callback == null) {
            return Ok(person); // {"id":1,"name":"Mike"}
        }
    
        var response = new HttpResponseMessage(HttpStatusCode.OK);
    
        var json = JsonConvert.SerializeObject(person);
    
        //functionName({"id":1,"name":"Mike"});
        var javascript = string.Format("{0}({1});", callback, json);
    
        response.Content = new StringContent(javascript, Encoding.UTF8, "text/plain");
    
        return ResponseMessage(response);
    }
    

    Of course you would need to do proper validation on the call back as this currently open up the API for script injection.