我是Angular 2中的新手。我将表格数据从角度2发送到webapi,但它无效。 的的WebAPI:
public class FetchDataController : ApiController
{
[HttpGet]
public IList<Student> ListOfStudents()
{
AppRepository objapp = new AppRepository();
IList<Student> objData = null;
objData = objapp.getStudent();
return objData;
}
[HttpPost]
[Route("PostStudent")]
public JsonResult<Boolean> PostStudent(Student value)
{
// Append text to an existing file named "WriteLines.txt".
string data = "ID: " + value.Id + ", FirstName: " + value.FirstName + ",LastName: " + value.LastName + ",Salary: " + value.salary;
using (StreamWriter outputFile = new StreamWriter(HttpContext.Current.Server.MapPath("~")+ "/TestVD/WriteLines.txt", true))
{
outputFile.WriteLine(data);
}
return Json(true);
}
}
我的WebAPIConfig.js如下。我在这里添加了CORS处理以及Webconfig文件:
var cors = new EnableCorsAttribute("http://localhost", "*", "*");
config.EnableCors(cors);
// Web API configuration and services
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "ListOfStudents",
routeTemplate: "api/{controller}/{id}",
defaults: new { controller = "FetchData", action = "ListOfStudents", id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "PostStudent",
routeTemplate: "api/{controller}/{id}",
defaults: new { controller = "FetchData", action = "PostStudent", id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
现在,从Angular 2开始,我可以使用学生webAPI方法列表显示数据,但是在发布时我得到&#34; 405(方法不允许)&#34;来自我的WEBAPI网址。 我正在接受WEBAPI post方法的回复。
ok
:
false
status
:
405
statusText
:
"Method Not Allowed"
type
:
2
url
:
"http://localhost/TestWebService/api/FetchData/"
_body
:
"{"Message":"The requested resource does not support http method 'POST'."}"
我的Angular 2服务代码如下
@Injectable()
export class RssService {
private studentUrl = "http://localhost/TestWebService/api/FetchData/";
constructor(private http: Http) { }
getStudentList() {
return this.http.get(this.studentUrl)
.map(res => <Student[]>res.json())
.catch(this.handleError);
}
private handleError(error: Response) {
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}
postStudent(model: any): Observable<any> {
let body = JSON.stringify(model);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
console.log('add Student start : ' + body);
return this.http.post(this.studentUrl , body, options)
.map((response: Response) => <any>response.json())
.catch(this.handleError);
}
}
你能帮帮我吗......
答案 0 :(得分:0)
您的PostStudent方法有一个路由属性[Route("PostStudent")]
。
因此,此操作的网址不是http://localhost/TestWebService/api/FetchData/
,而是http://localhost/TestWebService/PostStudent
。
要使用网址http://localhost/TestWebService/api/FetchData/
,只需删除此Route
属性。
如果您仍想使用特定路由进行PostStudent
操作并通过http://localhost/TestWebService/api/FetchData/PostStudent
访问它,请在您的控制器上添加RoutePrefix
属性:
[RoutePrefix("api/FetchData")]
public class FetchDataController : ApiController
查看此文章了解模式详情:Attribute Routing in ASP.NET Web API 2
答案 1 :(得分:0)
由于System.Net和System.Web命名空间,我已经解决了这个问题。这link给了我很多帮助。