【发布时间】:2015-08-21 01:41:15
【问题描述】:
我正在阅读 Designing Evolvable Web APIs with ASP.NET。在其中一个练习中,本书让我使用 Visual Studio 编辑控制器。这是在 ASP.NET 中使用 C# 完成的。我使用的模板是标准的 ASP.NET Web 应用程序 API。
我已将控制器编辑为书中显示的方式(尽管它似乎没有给出非常具体的指示)。这是我的控制器的样子。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.ModelBinding;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OAuth;
using WebApplication4.Models;
using WebApplication4.Providers;
using WebApplication4.Results;
namespace WebApplication4.Controllers
{
public class GreetingController : ApiController
{
public string GetGreeting() {
return "Hello World!";
}
}
public static List<Greeting> _greetings = new List<Greeting>();
public HttpResponseMessage PostGreeting(Greeting greeting)
{
_greetings.Add(greeting);
var greetingLocation = new Uri(this.Request.RequestUri, "greeting/" + greeting.Name);
var response = this.Request.CreateResponse(HttpStatusCodeResult.Created);
response.Headers.Location = greetingLocation;
return response;
}
}
我收到错误:
- _greetings:命名空间不能直接包含字段或方法等成员
- PostGreeting:命名空间不能直接包含字段或方法等成员,
- _greetings : 在当前上下文中不存在
- 请求:
<invalid-global-code>不包含“请求”的定义, - 已创建:HttpStatusCodeREsult 不包含“已创建”的定义
【问题讨论】:
-
请注意,您的代码不是线程安全的,并且不适用于并发请求。
-
旁注:在遇到类似问题之前,以其他人的身份搜索错误消息通常是个好主意。通常,带有错位大括号/逗号的帖子将作为“印刷错误”关闭,但如果您不喜欢这样,它可以作为许多“命名空间不能直接包含...”帖子之一的副本关闭,例如stackoverflow.com/questions/9383791/…。跨度>
-
@AlexeiLevenkov 我不认为这是印刷错误,因为我不清楚为什么需要移动支架。从下面的答案中,我看到 _greetings 应该是 greetingController 类的一部分,但我不明白类和列表(或它之后的代码)之间发生的关系。