我是.net web developpment的新手,我正在使用ASP.net开发一个rest API,问题是我希望通过名字让学生把它放在URL中,这是我的模型class Student.cs:
public partial class Student : BaseEntity
{
public string FirstName { get; set; }
public string LastName { get; set; }
//constructor of the Student
public Student()
{
Attendances = new List<Attendance>();
StudentComments = new List<StudentComment>();
}
}
这是我的dataBase数据初始化代码:SMADBInitializer.cs
var Students = new List<Student> //I get the error in this line
{
new Student{FirstName="sam", LastName="9"},
}
SMAContext.cs:
public partial class SMAContext : DataContext
{
static SMAContext()
{
Database.SetInitializer<SMAContext>(new SMADBInitializer());
}
public SMAContext()
: base("Name=SMAContext")
{
}
public DbSet<Student> Students { get; set; }
}
StudentsController.cs:
private static SMAContext cc = new SMAContext();
[Route("api/Students/{name:alpha}")]
public string Get(string name)
{
var query = from Students in cc.Students
where Students.FirstName.Contains(name)
select Students.FirstName;
var students = query.ToList();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, students);
return response.ToString();
}
这是RouteConfig类:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "GetStudentName",
url: "{controller}/{action}/{name}",
defaults: new { controller = "Home", action = "Index", name = UrlParameter.Optional }
);
}
}
从教程中,我已经评论了WebApiConfig文件的那些行:
config.MapHttpAttributeRoutes();
//config.Routes.MapHttpRoute(
// name: "DefaultApi",
// routeTemplate: "api/{controller}/{id}",
// defaults: new { id = RouteParameter.Optional }
//);
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
我创建了一个html文件,其中我放置了应用程序的所有URL,这是针对学生的名称选择:
<h4>Students</h4>
<a href="api/Students/sam" target="_blank">(GET => api/Students/sam) GetByName »</a><br />
问题在于,当我尝试在导航器中录制http://localhost:50001/api/Students/sam时,我收到此错误:
"ExceptionType":"System.NullReferenceException"
所以我在StudentsController
中得到了查询变量null感谢您的帮助:)