ASP.Net Web API Http 路由和非 JSON 响应
ASP.Net Web API Http routing and non JSON responses
我想模仿现有网络服务的行为。这是一个非常简单的示例,展示了我想要实现的目标。
我使用ASP.Net Web API路由:用它配置路由非常简单。
要求,第 1 部分:查询:
GET whatever.../Person/1
应returnJSON:
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
应returnjavascript:
Content-Type: text/plain; charset=utf-8
functionName({"id":1,"name":"Mike"});
有什么实现方法(第 2 部分)的想法吗?
需要修改 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 用于脚本注入。
我想模仿现有网络服务的行为。这是一个非常简单的示例,展示了我想要实现的目标。
我使用ASP.Net Web API路由:用它配置路由非常简单。
要求,第 1 部分:查询:
GET whatever.../Person/1
应returnJSON:
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
应returnjavascript:
Content-Type: text/plain; charset=utf-8
functionName({"id":1,"name":"Mike"});
有什么实现方法(第 2 部分)的想法吗?
需要修改 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 用于脚本注入。