首页 > 代码库 > C# 关于接口
C# 关于接口
一、关于接口
1、正常的写方法 功能主要是数据的接收和返回
1、返回xml
public class XmlResult:ActionResult
{
private object objectToSerialize;
public XmlResult(object objectToSerialize)
{
this.objectToSerialize = objectToSerialize;
}
public object ObjectToSerialize
{
get { return this.objectToSerialize; }
}
public override void ExecuteResult(ControllerContext context)
{
if (this.objectToSerialize != null)
{
context.HttpContext.Response.Clear();
var xs = new XmlSerializer(this.objectToSerialize.GetType());
context.HttpContext.Response.ContentType = "text/xml";
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
xs.Serialize(context.HttpContext.Response.Output, this.objectToSerialize, ns);
}
}
}
需要一个类来处理
只需要将产生的对象进行实例化 XmlResult xmlResult = new XmlResult(staEntity); staEntity为想要转换的对象
2、返回json
public class JsonpResult:JsonResult
{
private static readonly string JsonpCallbackName = "callback";
private static readonly string CallbackApplicationType = "application/json";
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if ((JsonRequestBehavior == JsonRequestBehavior.DenyGet) && string.Equals(context.HttpContext.Request.HttpMethod, "GET"))
{
throw new InvalidOperationException();
}
var response = context.HttpContext.Response;
if (!string.IsNullOrEmpty(ContentType))
{
response.ContentType = ContentType;
}
else
{
response.ContentType = CallbackApplicationType;
}
if (ContentEncoding != null)
{
response.ContentEncoding = this.ContentEncoding;
}
if (Data != null)
{
string buffer;
var request = context.HttpContext.Request;
var serializer = new JavaScriptSerializer();
if (request[JsonpCallbackName] != null)
{
buffer = string.Format("{0}({1})", request[JsonpCallbackName], serializer.Serialize(Data));
}
else
{
buffer = serializer.Serialize(Data);
}
response.Write(buffer);
}
}
}
返回的类型是JsonpResult
return this.Jsonp(resEntity);
C# 关于接口