【问题标题】:ASP.Net Web API Http routing and non JSON responsesASP.Net Web API Http 路由和非 JSON 响应
【发布时间】:2018-11-13 12:26:12
【问题描述】:

我想模仿现有网络服务的行为。这是一个非常简化的示例,显示了我想要实现的目标。

我使用 ASP.Net Web API 路由:用它配置路由非常简单。

要求,第 1 部分:查询:

GET whatever.../Person/1

应返回 JSON:

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

这是小菜一碟:

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"
    };
}

要求,第 2 部分:查询:

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

应返回 javascript:

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

任何想法如何实现这一点(第 2 部分)?

【问题讨论】:

    标签: c# asp.net-mvc asp.net-web-api asp.net-mvc-routing


    【解决方案1】:

    需要修改 ApiController 以满足所需的行为

    基于提供的代码的简单示例

    //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);
    }
    

    当然,您需要对回调进行适当的验证,因为这目前打开了用于脚本注入的 API。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-06
      • 1970-01-01
      • 2020-05-03
      • 2018-08-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多