0
点赞
收藏
分享

微信扫一扫

.net webapi


.net的webapi简单易用,但初做时,还是碰上路由的问题,记录下来备用
webapiconfig文件在app_start中,不存在的话手工加下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace Dcampus.SSO
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services

// Web API routes
config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}

需注意的地方: routeTemplate: “api/{controller}/{action}/{id}”,中间加上{action}

api控制器:

public class DataSrvController : ApiController
{
private class resultObject
{
public long count { get; set; }
public object data { get; set; }
public List<dynamic> jsonData { get; set; }
public string message { get; set; }
public object metaData { get; set; }
public bool success { get; set; }

}

public class paraObject
{
public string term { get; set; }
public string studentno { get; set; }
public string courseno { get; set; }
}

[HttpGet]
[HttpPost]
public HttpResponseMessage getcourse(string term = null, string studentno = null, int start = 0, int limit = 0)
{

var robj = new resultObject();
try
{
var lobj = DataAll.Api.getCourse(term, studentno, start, limit);
robj.success = true;
robj.count = lobj.total;
robj.jsonData = lobj.rows;
}
catch (Exception e)
{
robj.message = e.Message;
}

return new HttpResponseMessage { Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(robj), System.Text.Encoding.UTF8, "application/json") };
}

[HttpGet]
[HttpPost]
public void setsuccess()
{
var sr = new StreamReader(System.Web.HttpContext.Current.Request.InputStream);
var stream = sr.ReadToEnd();
var list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<paraObject>>(stream);
var i = 0;
}
}

两个方法,getcourse提供输出,setsuccess提供输入,输入时接收的参数是个json字符串


举报

相关推荐

0 条评论